map filter reduce Examples
Short, runnable programs that show python map, filter and reduce in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python map, filter and reduce lesson.
1Built-in functions as the rule
int, len and str.upper already do what you need, so there is no need for a lambda. Pass them without parentheses.
raw_ages = ["21\n", "34\n", "19\n"]
ages = list(map(int, map(str.strip, raw_ages)))
print(ages)
print(max(ages), round(sum(ages) / len(ages), 1))
print(list(map(len, ["tea", "coffee", "milk"])))
print(list(map(str.upper, ["ok", "fail"])))Expected output[21, 34, 19]
34 24.7
[3, 6, 4]
['OK', 'FAIL']
2map over three lists at once
With three iterables, the function takes three arguments. map stops when the shortest list ends, so each product, price and quantity must line up.
items = ["pen", "ink", "tape"]
prices = [1.5, 8.0, 2.25]
quantities = [4, 1, 2]
lines = map(lambda item, price, qty: f"{item}: {price * qty:.2f}", items, prices, quantities)
for line in lines:
print(line)Expected outputpen: 6.00
ink: 8.00
tape: 4.50
3filter with a named test function
When the test needs more than one expression, give it a name. The same function can be reused to find the valid ones, or, with not, the invalid ones.
def is_valid_email(text):
return "@" in text and "." in text.split("@")[-1]
signups = ["asha@mail.com", "ben.at.mail", "chen@mail", "mia@work.org"]
print(list(filter(is_valid_email, signups)))
print(list(filter(lambda s: not is_valid_email(s), signups)))Expected output['asha@mail.com', 'mia@work.org']
['ben.at.mail', 'chen@mail']
4Merging settings with reduce
Here the combining step is custom: merge the next layer of settings over the result so far. Later layers win, and the empty dictionary is the starting point.
from functools import reduce
defaults = {"theme": "light", "font": 12, "lang": "en"}
team = {"font": 14}
user = {"theme": "dark"}
settings = reduce(lambda merged, layer: {**merged, **layer}, [defaults, team, user], {})
print(settings)Expected output{'theme': 'dark', 'font': 14, 'lang': 'en'}
5Longest word: reduce versus max
reduce keeps the best word so far. The > means that on a tie the earlier word stays, which matches what max(..., key=len) does. Prefer the built-in when one exists.
from functools import reduce
words = ["pear", "banana", "fig", "cherry"]
longest = reduce(lambda best, word: word if len(word) > len(best) else best, words)
print(longest)
print(max(words, key=len))Expected outputbanana
banana
6map is lazy: nothing runs until you ask
Creating the map object prints nothing. The function runs only when next() or list() asks for a result, and one item at a time.
def shout(word):
print("processing", word)
return word.upper()
results = map(shout, ["tea", "milk"])
print("map created")
print(next(results))
print(list(results))Expected outputmap created
processing tea
TEA
processing milk
['MILK']
Practise next
Python map, filter and reduce exercises → Back to the lesson
Python Lambda Functions examplesPython List Comprehensions examplesPython Iterators examplesPython any() and all() examples