Python Lambda / Anonymous Function

1. What is a Lambda Function

A lambda function is a small anonymous function defined using the lambda keyword. It can have any number of arguments but only one expression.

square = lambda x: x ** 2
print(square(5))  # Output: 25

Lambda functions are used for concise, one-line operations.


2. Lambda with Multiple Arguments

add = lambda a, b: a + b
print(add(10, 5))  # Output: 15

Supports multiple inputs with a single return expression.


3. Lambda Without Assignment (Inline Usage)

print((lambda x, y: x * y)(4, 5))  # Output: 20

Lambda can be defined and executed immediately.


4. Lambda with map()

numbers = [1, 2, 3, 4]

squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # Output: [1, 4, 9, 16]

Used to apply a function to each item in an iterable.


5. Lambda with filter()

Filters elements based on a condition.


6. Lambda with reduce()

Reduces an iterable to a single result.


7. Lambda for Sorting Key

Lambda is commonly used as a custom sorting key.


8. Lambda in List Comprehension Context

Demonstrates functional programming patterns.


9. Lambda vs Normal Function

Lambda is more concise but less suitable for complex logic.


10. Real-World Lambda Example

Lambda enables expressive data processing in analytics and business logic.

Last updated