Lambda Functions
A lambda function is a small anonymous function defined with the `lambda` keyword. It can take any number of arguments but returns only one expression. Lambdas are often used for short, throwaway functions, especially with `map()`, `filter()`, and `sorted()`.
Syntax
`lambda arguments: expression`
square = lambda x: x * x
print(square(5)) # 25
Using with map()
`map()` applies a function to every item of an iterable.
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, numbers))
print(squares) # [1, 4, 9, 16]
Using with filter()
`filter()` returns items where the function returns True.
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even) # [2, 4]
Using with sorted()
Custom sort key with lambda.
students = [("Alice", 25), ("Bob", 20), ("Charlie", 23)]
sorted_by_age = sorted(students, key=lambda x: x[1])
print(sorted_by_age) # [('Bob',20), ('Charlie',23), ('Alice',25)]
Two Minute Drill
- Lambda functions are anonymous, single‑expression functions.
- Often used with `map()`, `filter()`, `sorted()`.
- Useful for short operations where a full function definition would be overkill.
- Cannot contain statements (only expressions).
Need more clarification?
Drop us an email at career@quipoinfotech.com
