Python Lambda
A lambda function is a small anonymous function. (a function without a name.)
A lambda function can take any number of arguments, but can only have one
expression.
Syntax
lambda arguments : expression
The expression is executed and the result is returned:
Example
Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
Example
Summarize argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
🔹 1. map(): Apply a function to each item in a list.
Use: When you want to change or transform every item in a list.
Syntax: map(function, iterable)
Example:
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16]
🔹 2. filter(): Filter items based on a condition.
Use: When you want to select items from a list based on some rule.
Syntax: filter(function, iterable)
Example:
numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even) # Output: [2, 4, 6]
🔹 3. reduce(): Apply a function to accumulate values.
Use: When you want to combine all items into a single value (e.g., sum, product).
Import it first: from functools import reduce
Syntax: reduce(function, iterable)
Example:
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24 (1*2*3*4)
🔸 Summary Table:
Function Purpose Output Example
map() Transform all items [1, 4, 9, 16]
filter() Select items based on [2, 4, 6]
condition
reduce() Combine all items to one 24
value