Lambda, map, filter and reduce
A lambda is a small unnamed function written in one line: lambda x: x * 2. map() applies a function to every item, filter() keeps items where a function returns true, and reduce() combines items into one value. In modern Python, lambdas shine as the key for sorted(), min() and max(), while comprehensions usually replace map and filter.
Functions are values
def shout(text: str) -> str:
return text.upper() + "!"
speak = shout # no brackets: the function itself
print(speak("hello"))
actions = [str.upper, str.lower, shout]
for action in actions:
print(action("Hi"))HELLO! HI hi HI!
Because functions are values, you can store them, put them in lists and pass them to other functions. Everything in this lesson builds on that idea.
lambda
double = lambda x: x * 2
print(double(21))
add = lambda a, b: a + b
print(add(2, 3))42 5
The best use: sort keys
people = [("Ana", 31), ("Ben", 25), ("Cara", 38)]
print(sorted(people, key=lambda p: p[1]))
print(max(people, key=lambda p: p[1]))
files = ["b.txt", "A.csv", "c.py"]
print(sorted(files, key=str.lower))[('Ben', 25), ('Ana', 31), ('Cara', 38)]
('Cara', 38)
['A.csv', 'b.txt', 'c.py']map() and filter()
raw = [" 12 ", "7", " 30"]
numbers = list(map(int, raw))
print(numbers)
big = list(filter(lambda n: n > 10, numbers))
print(big)
# the same with comprehensions
print([int(s) for s in raw])
print([n for n in numbers if n > 10])[12, 7, 30] [12, 30] [12, 7, 30] [12, 30]
map(int, raw) is neat when you already have a named function. For anything that needs a lambda, a comprehension is usually easier to read.
reduce()
from functools import reduce
import math
numbers = [2, 3, 4]
print(reduce(lambda acc, n: acc * n, numbers))
print(math.prod(numbers)) # the built-in way24 24
reduce walks through the list carrying a running result. Python already has sum(), math.prod(), max() and "".join() for the common cases — use those first.
any(), all() and partial()
from functools import partial
scores = [72, 88, 95]
print(all(s >= 50 for s in scores))
print(any(s > 90 for s in scores))
def power(base: float, exponent: float) -> float:
return base ** exponent
square = partial(power, exponent=2)
print(square(9))True True 81
Practice
Sort products = [("mug", 8.5), ("tea", 3.0), ("lamp", 24.0)] from most to least expensive and print the result. Then print only the names of products under 10, using any approach you like.
[('lamp', 24.0), ('mug', 8.5), ('tea', 3.0)]
['mug', 'tea']