Python includes functions that loop over collections and combine or transform them. They are very convenient, and they are often equivalent to a comprehension.
map: applying a function to all
map(function, collection) applies the function to each element. It returns an iterator, which is turned into a list with list():
numbers = [1, 2, 3, 4]
doubles = list(map(lambda n: n * 2, numbers))
print(doubles) # [2, 4, 6, 8]
integers = list(map(int, "4 8 15".split()))
print(integers) # [4, 8, 15]
list(map(int, input().split())) is the classic way to read a line of numbers. It is equivalent to [int(x) for x in input().split()].
filter: keeping some
filter(function, collection) keeps the elements for which the function returns True:
numbers = [3, -1, 4, 0, -5, 2]
positives = list(filter(lambda n: n > 0, numbers))
print(positives) # [3, 4, 2]
filter and map can be chained:
doubled_positives = list(map(lambda n: n * 2, filter(lambda n: n > 0, numbers)))
print(doubled_positives) # [6, 8, 4]
map and filter or a comprehension?
# Both forms do the same:
list(map(lambda n: n * 2, filter(lambda n: n > 0, numbers)))
[n * 2 for n in numbers if n > 0]
The comprehension is usually more readable, and it is the one most Python programmers prefer. It is worth knowing map and filter to understand other people's code and because with existing functions (map(int, ...)) they look very clean.
zip: looping over several lists at once
zip joins the elements that occupy the same position in several collections:
names = ["ana", "luis", "eva"]
grades = [8, 6, 9]
for name, grade in zip(names, grades):
print(f"{name}: {grade}")
# ana: 8
# luis: 6
# eva: 9
print(list(zip(names, grades))) # [('ana', 8), ('luis', 6), ('eva', 9)]
If the collections have different lengths, zip stops at the shortest one. It is ideal for operating element by element:
a = [1, 2, 3]
b = [4, 5, 6]
sums = [x + y for x, y in zip(a, b)]
print(sums) # [5, 7, 9]
print(sum(x * y for x, y in zip(a, b))) # 32 (dot product)
dictionary = dict(zip(names, grades))
print(dictionary) # {'ana': 8, 'luis': 6, 'eva': 9}
enumerate: the index and the value
When you need the position of each element, enumerate avoids keeping a counter by hand:
tasks = ["buy bread", "study", "exercise"]
for i, task in enumerate(tasks):
print(i, task)
# 0 buy bread
# 1 study
# 2 exercise
for i, task in enumerate(tasks, start=1):
print(f"{i}. {task}")
# 1. buy bread
# 2. study
# 3. exercise
It is much better than for i in range(len(tasks)) and then tasks[i].
Summary
| Function | What it is for |
|---|---|
map(f, data) | apply f to each element |
filter(f, data) | keep those that satisfy f |
zip(a, b) | pair up elements of several collections |
enumerate(data) | get index and value at once |
sorted(data, key=f) | sort according to f |
Practice in Adding lists with zip, Number the lines and Double the positives.