After this lesson you can transform every item of a list, keep only the items you want, and walk two lists side by side, using three built-in helpers.
map: do something to every item
map takes a function and an iterable, and applies the function to each item. Say the shop stores prices as text and needs numbers:
prices_text = ["120", "250", "60"]
prices = list(map(int, prices_text))
print(prices)[120, 250, 60]The result of map is not a list but a lazy iterator, which produces values only when asked. That is why the example wraps it in list(). If you print the raw map, you see an object, not the values:
result = map(int, prices_text)
print(type(result))
print(list(result))
print(list(result))<class 'map'>
[120, 250, 60]
[]Notice that the second list(result) is empty. An iterator can be used only once, and the first call used it up.
You can pass any function, including a lambda or your own:
def with_tax(price):
return round(price * 1.18, 2)
print(list(map(with_tax, [100, 250])))
print(list(map(lambda word: word.upper(), ["tea", "milk"])))[118.0, 295.0]
['TEA', 'MILK']With two lists, map takes two arguments for the function:
print(list(map(lambda a, b: a * b, [1, 2, 3], [10, 20, 30])))[10, 40, 90]filter: keep only some items
filter also takes a function and an iterable. It keeps the items for which the function returns a true value.
marks = [35, 82, 47, 91, 28]
passed = list(filter(lambda m: m >= 40, marks))
print(passed)[82, 47, 91]If you pass None as the function, it keeps the truthy items, which is a quick way to drop empty values:
raw = ["tea", "", "milk", "", "eggs"]
print(list(filter(None, raw)))['tea', 'milk', 'eggs']zip: walk lists side by side
zip pairs up items by position. It is the tool to use when you have related lists, such as names and marks.
names = ["Asha", "Ben", "Chloe"]
marks = [82, 91, 77]
for name, mark in zip(names, marks):
print(name, mark)
print(list(zip(names, marks)))Asha 82
Ben 91
Chloe 77
[('Asha', 82), ('Ben', 91), ('Chloe', 77)]If the lists differ in length, zip stops at the shortest one and silently ignores the rest:
print(list(zip([1, 2, 3], ["a", "b"])))[(1, 'a'), (2, 'b')]Zip also builds dictionaries neatly, and zip(*pairs) can pull pairs apart again:
lookup = dict(zip(names, marks))
print(lookup)
pairs = [("a", 1), ("b", 2)]
letters, numbers = zip(*pairs)
print(letters, numbers){'Asha': 82, 'Ben': 91, 'Chloe': 77}
('a', 'b') (1, 2)enumerate: numbered items
When you need each item together with its position, use enumerate instead of a counter variable.
for number, name in enumerate(names, start=1):
print(number, name)1 Asha
2 Ben
3 ChloeComprehensions as an alternative
Most Python programmers write the same ideas as list comprehensions, which read left to right:
print([int(text) for text in prices_text])
print([m for m in [35, 82, 47, 91, 28] if m >= 40])[120, 250, 60]
[82, 47, 91]A good rule of thumb: when you already have a named function, such as int, map(int, items) is short and clear. When you would need a lambda, a comprehension is usually easier to read. Use whichever your team finds clearer, but be consistent.
Putting the tools together
Real tasks often combine these helpers. Imagine a list of product names with their prices as text. You want a tidy report of those that cost more than 100, with the price as a number:
names = ["tea", "milk", "coffee"]
price_text = ["120", "60", "250"]
priced = zip(names, map(int, price_text))
expensive = filter(lambda pair: pair[1] > 100, priced)
for name, price in expensive:
print(f"{name}: {price}")tea: 120
coffee: 250Because zip, map and filter all produce lazy iterators, nothing is calculated until the for loop asks for values, and no big intermediate lists are created. That laziness matters when the data is large, for example when reading a file line by line.
Common mistakes
- Printing the map or filter object and wondering why it shows
<map object ...>. Wrap it inlist(). - Using the iterator twice. After one pass it is empty. Store the list if you need it again.
- Assuming zip complains about unequal lengths. It stops at the shortest one without a warning, so check the lengths if that matters.
- Passing the result of a call to map. Write
map(with_tax, prices), notmap(with_tax(), prices). Pass the function itself. - Reaching for filter with a lambda when a comprehension is clearer.
Treating a map object like a list is a related mistake that raises an error:
numbers = map(int, ["1", "2"])
print(numbers[0])TypeError: 'map' object is not subscriptableExercise
Given names = ["asha", "ben", "chloe"] and scores = [82, 91, 77], produce a list of strings such as "Asha: 82", where the name is capitalised, but include only the students whose score is at least 80. Use zip and a comprehension.
Show one possible answer
names = ["asha", "ben", "chloe"]
scores = [82, 91, 77]
lines = [f"{name.capitalize()}: {score}" for name, score in zip(names, scores) if score >= 80]
print(lines)['Asha: 82', 'Ben: 91']Key points
- map(function, items) applies a function to every item. filter(function, items) keeps the items for which the function is true.
- map and filter return lazy iterators, so wrap them in list() to see the results.
- zip(a, b) pairs items by position and stops at the shorter input.
- enumerate gives each item a number and is often neater than a manual counter.
- A list comprehension can do the work of map and filter and is usually easier to read.