Python Lambda, map() and filter()
A lambda is a tiny function without a name, and map() and filter() use functions to process whole lists at once.
Lambda Syntax
A lambda is written in one line:
Example
lambda parameters: expressionIt has no def, no name and no return. The value of the expression is returned automatically.
Example
add_tax = lambda price: round(price * 1.18)
area = lambda w, h: w * h
print(add_tax(500))
print(area(12, 10))590 120
These two lines work the same as normal functions. But giving a lambda a name like this is not the usual way to use it. Lambdas shine when you pass them into another function.
Lambda as a Sort Key
sorted(), min() and max() take a key function. It tells Python what to compare.
Example
products = [
{"name": "Mouse", "price": 1200},
{"name": "Keyboard", "price": 3500},
{"name": "USB cable", "price": 350},
]
by_price = sorted(products, key=lambda p: p["price"])
print([p["name"] for p in by_price])
print(max(products, key=lambda p: p["price"])["name"])
names = ["sara", "Ali", "bilal", "Zara"]
print(sorted(names))
print(sorted(names, key=lambda n: n.lower()))['USB cable', 'Mouse', 'Keyboard'] Keyboard ['Ali', 'Zara', 'bilal', 'sara'] ['Ali', 'bilal', 'sara', 'Zara']
Without a key, capital letters sort before small ones. With key=lambda n: n.lower() the sort ignores case.
map(): Change Every Item
map(function, collection) calls the function on every item. It returns a map object, so wrap it in list() to see the values.
Example
prices_usd = [10, 25, 4]
rate = 280
prices_pkr = list(map(lambda d: d * rate, prices_usd))
print(prices_pkr)
typed = ["12", "7", "30"]
numbers = list(map(int, typed))
print(numbers, sum(numbers))[2800, 7000, 1120] [12, 7, 30] 49
You can pass any function to map(), not only a lambda. map(int, typed) turns every string into a number.
filter(): Keep Some Items
filter(function, collection) keeps only the items for which the function returns True.
Example
ages = [15, 22, 17, 30, 12, 19]
adults = list(filter(lambda a: a >= 18, ages))
print(adults)
phones = ["03001234567", "12345", "03219876543", "0300"]
valid = list(filter(lambda p: len(p) == 11 and p.startswith("03"), phones))
print(valid)[22, 30, 19] ['03001234567', '03219876543']
reduce(): Combine Into One Value
reduce() lives in the functools module. It takes the first two items, combines them, then combines the result with the next item, and so on.
Example
from functools import reduce
numbers = [2, 3, 4, 5]
product = reduce(lambda a, b: a * b, numbers)
print(product)120
The steps are: 2 x 3 = 6, then 6 x 4 = 24, then 24 x 5 = 120.
map/filter or a Comprehension?
Both styles give the same result. Many Python developers find comprehensions easier to read.
| Task | map / filter | Comprehension |
|---|---|---|
| Double each number | list(map(lambda x: x * 2, nums)) | [x * 2 for x in nums] |
| Keep even numbers | list(filter(lambda x: x % 2 == 0, nums)) | [x for x in nums if x % 2 == 0] |
| Convert to int | list(map(int, items)) | [int(i) for i in items] |
Use map() when you already have a named function, like map(int, items) or map(str.upper, words). When you would need a lambda, a comprehension is usually cleaner.
Limits of Lambda
- A lambda can hold only one expression. No loops, no
ifblocks, no multiple lines. - It can use a short conditional expression:
lambda m: "Pass" if m >= 50 else "Fail". - If the logic grows, write a normal function with
defand a clear name.
Exercise
Exercise
What does list(filter(lambda x: x > 3, [1, 5, 2, 8])) return?
