from functools import reducenums = [1, 2, 3, 4]list(map(lambda x: x**2, nums)) # [1, 4, 9, 16]list(filter(lambda x: x % 2 == 0, nums)) # [2, 4]reduce(lambda acc, x: acc + x, nums) # 10, cumulative reductionreduce(lambda acc, x: acc + x, nums, 100) # 110, with an initial value
Comprehensions are often more Pythonic than map/filter
[x**2 for x in nums] is generally preferred over list(map(lambda x: x**2, nums)) for readability. map/filter shine mainly when passing an EXISTING named function without wrapping it in a lambda: map(str, nums).
When NOT to Use Lambda
Do not assign lambdas to a name
square = lambda x: x ** 2 # PEP 8 discourages this
If it needs a name, it deserves a proper def:
def square(x): return x ** 2
Named def functions get better tracebacks (the function name shows up in error messages instead of <lambda>), support docstrings, and support multiple statements.
Limitations
Only a single expression, no statements (no if blocks with bodies, no loops, no assignments via =).
Can use a conditional EXPRESSION though:
classify = lambda x: "even" if x % 2 == 0 else "odd"classify(4) # 'even'
No type annotations directly on lambda parameters (unlike regular def functions).