Python Functions and Methods: A Topic-by-Topic Reference · Lesson 9 of 12

Lesson 9: map, filter, zip, enumerate and Lambda

Looping tools that make code shorter: enumerate, zip, map, filter, reduce, lambda, iter/next, plus the walrus operator.

Lesson 9: map, filter, zip, enumerate and Lambda

enumerate()

enumerate(iterable, start=0)

Gives (position, item) pairs, so you do not need a counter variable.

for i, city in enumerate(["Kathmandu", "Pokhara", "Biratnagar"], start=1):
    print(i, city)

Output:

1 Kathmandu
2 Pokhara
3 Biratnagar

zip()

zip(a, b, ...)

Walks several iterables side by side, stopping at the shortest.

names = ["Ram", "Sita", "Hari"]
marks = [80, 92, 75]
for n, m in zip(names, marks):
    print(n, m)
print(list(zip("abc", [1, 2])))

Output:

Ram 80
Sita 92
Hari 75
[('a', 1), ('b', 2)]

zip(*pairs): unzipping and transposing

The star spreads a list into arguments, which reverses a zip.

pairs = [("a", 1), ("b", 2), ("c", 3)]
letters, numbers = zip(*pairs)
print(letters, numbers)
matrix = [[1, 2, 3], [4, 5, 6]]
print([list(r) for r in zip(*matrix)])

Output:

('a', 'b', 'c') (1, 2, 3)
[[1, 4], [2, 5], [3, 6]]

map() and filter()

map(function, iterable)

Applies a function to every item (lazily; wrap in list()).

print(list(map(str.upper, ["a", "b"])))
print(list(map(lambda n: n * 2, [1, 2, 3])))
print(list(map(int, "1 2 3".split())))
print(list(map(lambda a, b: a + b, [1, 2], [10, 20])))

Output:

['A', 'B']
[2, 4, 6]
[1, 2, 3]
[11, 22]

filter(function, iterable)

Keeps the items for which the function returns True. filter(None, x) drops falsy items.

print(list(filter(lambda n: n % 2 == 0, range(10))))
print(list(filter(None, [0, 1, "", "a", None, []])))

Output:

[0, 2, 4, 6, 8]
[1, 'a']

A list comprehension is usually clearer than map or filter with a lambda: [n * 2 for n in nums if n > 0]. Use map when you already have a named function.

lambda

lambda arguments: expression

A small unnamed function, written in one line. Its value is the expression.

square = lambda n: n * n
add = lambda a, b=10: a + b
print(square(7))
print(add(5), add(5, 1))
print((lambda x: x + 1)(41))

Output:

49
15 6
42

reduce()

functools.reduce(function, iterable, start)

Combines the items of an iterable into one value, two at a time.

from functools import reduce
print(reduce(lambda a, b: a + b, [1, 2, 3, 4]))
print(reduce(lambda a, b: a * b, range(1, 6)))
print(reduce(max, [3, 9, 2]))

Output:

10
120
9

Iterators

iter(x) and next(it, default)

Step through an iterable manually.

it = iter([10, 20])
print(next(it))
print(next(it))
print(next(it, "done"))

Output:

10
20
done

reversed, sorted, sum, min, max on iterators

These all accept any iterable, including generators and map objects.

nums = map(int, ["3", "1", "2"])
print(sorted(nums))

Output:

[1, 2, 3]

Generators: yield

A function that produces values one at a time and pauses between them. It uses almost no memory.

def countdown(n):
    while n > 0:
        yield n
        n -= 1

print(list(countdown(4)))
print(sum(countdown(100)))

Output:

[4, 3, 2, 1]
5050

The walrus operator :=

Assign and use a value in the same expression (Python 3.8+).

data = [4, 9, 16]
if (n := len(data)) > 2:
    print(f"{n} items, too many")

Output:

3 items, too many

Try it yourself

  1. Use zip to build a dictionary from two lists.
  2. Use enumerate to print only the items at even positions.
  3. Use reduce to find the largest of a list without max.

Next lesson: files, JSON and dates.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 9: map, filter, zip, enumerate and Lambda | MeroSir