Lambda, map, filter & sorted
Lambda: tiny anonymous functions
lambda x: x * 2 is a one-expression function without a name. Use it for short throwaway logic, usually as an argument to another function.
Functions are values
You can pass a function to another function. These built-ins take one:
| Function | What it does |
|---|---|
map(f, items) | apply f to every item |
filter(f, items) | keep items where f returns True |
sorted(items, key=f) | sort by f(item) |
max/min(items, key=f) | find the biggest/smallest by f |
functools.reduce(f, items) | combine everything into one value |
map and filter return lazy iterators, so wrap them in list() to see the result.
Comprehension or map/filter?
Most Python developers find comprehensions easier to read:
[x ** 2 for x in nums] instead of list(map(lambda x: x ** 2, nums)).
💡 sorted(..., key=...) is the most useful one here. Sort people by age, words by length, products by price.
▶️ Runs in the app.
Example
from functools import reduce
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
product = reduce(lambda a, b: a * b, nums)
print(squared, evens, product) # [1, 4, 9, 16, 25] [2, 4] 120
people = [("Ana", 25), ("Ben", 19), ("Cara", 31)]
by_age = sorted(people, key=lambda p: p[1])
print(by_age) # [('Ben', 19), ('Ana', 25), ('Cara', 31)]
print(max(people, key=lambda p: p[1])[0]) # Cara
words = ["banana", "kiwi", "apple"]
print(sorted(words, key=len)) # ['kiwi', 'apple', 'banana']