Python Lambda
Anonymous, one-line functions — great for short, throwaway operations.
Syntax
Python
# lambda arguments: expression
square = lambda x: x ** 2
square(5) # 25
add = lambda x, y: x + y
add(3, 4) # 7
greeting = lambda name: f"Hello, {name}!"
greeting("Raman") # "Hello, Raman!"
Lambda with sorted()
Python
people = [
{"name": "Charlie", "age": 30},
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 35},
]
# Sort by age:
sorted(people, key=lambda p: p["age"])
# Sort by name length:
sorted(people, key=lambda p: len(p["name"]))
Lambda with filter()
Python
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
# [2, 4, 6]
Lambda with map()
Python
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, nums))
# [1, 4, 9, 16, 25]
# Equivalent list comprehension (usually preferred):
squares = [x**2 for x in nums]
Lambda vs def
| Lambda | def |
|---|---|
| One expression only | Multiple statements |
| No docstring | Supports docstrings |
| Anonymous (no name) | Has a name |
| Best as key= argument | Best for reusable logic |
PEP 8 guidance
Don't assign a lambda to a variable — use
def instead. If you need a name for it, it's complex enough to warrant def. Lambdas shine when passed inline: sorted(data, key=lambda x: x['score']).