Sub topic 11
Useful tools from itertools
This chapter assumes you can write generator functions and generator expressions, and that you know iterators are single-use. If yield or next() still feels unfamiliar, review the earlier chapters first.
The itertools module in the standard library holds ready-made iterator building blocks. Each tool returns a lazy iterator, so it fits into the pipelines from the previous chapter and works on infinite streams.
Slicing a stream with islice
Ordinary slicing (seq[2:5]) does not work on generators, because they have no length and no indexing. islice(iterable, stop) or islice(iterable, start, stop, step) gives you the same effect lazily.
from itertools import islice
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
print(list(islice(fibonacci(), 8))) # [0, 1, 1, 2, 3, 5, 8, 13]The infinite generator is safe because islice stops pulling values after the eighth one.
Combining and chaining
A few tools join or pair iterables without building intermediate lists.
from itertools import chain, count, zip_longest
print(list(chain([1, 2], (3, 4), "ab")))
# [1, 2, 3, 4, 'a', 'b']
for n, letter in zip(count(1), "xyz"):
print(n, letter) # 1 x, 2 y, 3 z
print(list(zip_longest([1, 2, 3], "ab", fillvalue="-")))
# [(1, 'a'), (2, 'b'), (3, '-')]chain(*iterables)walks several iterables one after another.count(start, step)is an infinite counter. Pair it withzipto number items, which ends when the shorter input ends.zip_longestkeeps going until the longest input ends and fills gaps withfillvalue. Plainzipstops at the shortest.
Filtering and grouping
takewhile and dropwhile cut a stream at the first point where a condition fails.
from itertools import takewhile, dropwhile, groupby
data = [1, 3, 5, 6, 7, 9]
print(list(takewhile(lambda x: x % 2 == 1, data))) # [1, 3, 5]
print(list(dropwhile(lambda x: x % 2 == 1, data))) # [6, 7, 9]
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
for letter, group in groupby(words, key=lambda w: w[0]):
print(letter, list(group))
# a ['apple', 'avocado']
# b ['banana', 'blueberry']
# c ['cherry']takewhile stops at the first failure, even if later items would pass. That differs from filter, which tests every item.
groupby only groups adjacent items with the same key. Sort the data by the same key first if equal keys may be scattered. Each group is itself a lazy iterator that shares the source, so consume it before moving to the next key.
Splitting one iterator with tee
Because iterators are single-use, you cannot loop over one twice. tee(iterable, n) returns n independent iterators over the same source.
from itertools import tee
squares = (x * x for x in range(4))
first, second = tee(squares)
print(list(first)) # [0, 1, 4, 9]
print(list(second)) # [0, 1, 4, 9]Choosing a tool
| Need | Tool |
|---|---|
| First N items of a stream | `islice` |
| One sequence from many | `chain` |
| Infinite counter | `count` |
| Stop at first failing item | `takewhile` |
| Skip a leading run | `dropwhile` |
| Runs of equal keys | `groupby` |
| Several passes over one iterator | `tee` |
Exercise
What does this print, and why? from itertools import groupby print([k for k, _ in groupby("aabaa")])
Show answer
It prints ['a', 'b', 'a']. groupby groups only adjacent equal keys, so the two runs of "a" are separate groups, split by "b". Sorting the input first would give ['a', 'b'].
Exercise
Write an expression that returns the first five even numbers from an infinite counter starting at 0, without building a full list of the stream.
Show answer
list(islice((n for n in count(0) if n % 2 == 0), 5)) returns [0, 2, 4, 6, 8]. Import islice and count from itertools. The generator expression is lazy, and islice stops it after five values.