It can have any number of arguments, but only one expression.
lambda arguments: expression
Feature | Description |
---|---|
Anonymous | No need to name the function |
Single Expression | Must return the result of one expression |
Return Value | Automatically returns the result |
Used With | map() , filter() , reduce() , sorted() |
square = lambda x: x * x
print(square(5)) # Output: 25
This is equivalent to:
def square(x):
return x * x
add = lambda a, b: a + b
print(add(3, 7)) # Output: 10
map()
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
print(squared) # Output: [1, 4, 9, 16]
filter()
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [2, 4, 6]
sorted()
with Custom Keynames = ['Abhi', 'John', 'Zack', 'Mark']
sorted_names = sorted(names, key=lambda x: x[-1])
print(sorted_names)
# Output: ['Zack', 'Mark', 'Abhi', 'John']
reduce()
(from functools
)from functools import reduce
product = reduce(lambda x, y: x * y, [1, 2, 3, 4])
print(product) # Output: 24
Do ✅ | Don't ❌ |
---|---|
Use for simple one-liners | Avoid for complex logic |
Use with map , filter , sorted |
Avoid nested lambda functions |
Keep it readable and meaningful | Don’t overuse; use def if better |
When the function logic is complex or multi-line
When you need reusability or documentation (docstrings)
When you need clarity (named functions are easier to debug)