Learn / Intermediate / Lesson 2

Lambda, map, filter and reduce

10 min Tested on Python 3.15Updated By
In short

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

Python
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"))
Output
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

Python
double = lambda x: x * 2
print(double(21))

add = lambda a, b: a + b
print(add(2, 3))
Output
42
5

The best use: sort keys

Python
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))
Output
[('Ben', 25), ('Ana', 31), ('Cara', 38)]
('Cara', 38)
['A.csv', 'b.txt', 'c.py']

map() and filter()

Python
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])
Output
[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()

Python
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 way
Output
24
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()

Python
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))
Output
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.

Expected output:
[('lamp', 24.0), ('mug', 8.5), ('tea', 3.0)]
['mug', 'tea']
Your code

Quick check

1. What does list(map(len, ["a", "bb"])) give?

2. What is the most common good use of lambda today?

3. What does all([]) return?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →