Sub topic 3
Infinite streams with count, cycle and repeat
This chapter assumes you know Python loops, functions and generators at a basic level, and that you understand the difference between an iterable and an iterator from the earlier chapters. It covers the three infinite iterators in itertools: count, cycle and repeat.
What makes a stream infinite
An infinite iterator never raises StopIteration on its own. Each call to next() produces another value, so it is safe only when something else decides when to stop. That something can be a break in a loop, a bounded consumer such as zip, or islice, which the next chapter covers in full.
Because the values are produced one at a time, an infinite iterator uses constant memory. It stores a small amount of state, such as the current number, and nothing else.
count: an endless counter
count(start=0, step=1) yields start, start + step, start + 2 * step, and so on. It accepts floats and Fraction values as well as integers.
from itertools import count
counter = count(10, 5)
print(next(counter))
print(next(counter))
print(next(counter))This prints 10, 15 and 20. A common use is numbering items without keeping a separate index variable. zip stops when its shortest input ends, so the endless count is cut off by the finite list.
from itertools import count
names = ['ada', 'grace', 'alan']
for number, name in zip(count(1), names):
print(number, name)This is similar to enumerate(names, 1). Prefer enumerate when you only need an index. count is more useful when you need a custom step or when you are pairing several streams.
cycle: repeat a sequence forever
cycle(iterable) walks through the input once, saving each item, and then replays the saved items in order without end.
from itertools import cycle
colors = cycle(['red', 'green', 'blue'])
for _, row in zip(range(5), colors):
print(row)The output is red, green, blue, red, green. Typical uses are alternating row styles, round-robin assignment of jobs to workers, and repeating a short pattern across a longer sequence.
from itertools import cycle
workers = cycle(['w1', 'w2'])
jobs = ['a', 'b', 'c', 'd', 'e']
print(list(zip(jobs, workers)))This prints [('a', 'w1'), ('b', 'w2'), ('c', 'w1'), ('d', 'w2'), ('e', 'w1')].
An empty input gives an empty cycle. It ends immediately instead of looping forever.
repeat: the same value again and again
repeat(object, times=None) yields the same object. Without times it never stops. With times it stops after that many items.
from itertools import repeat
print(list(repeat('ab', 3)))
print(list(map(pow, [2, 3, 4], repeat(2))))The first line prints ['ab', 'ab', 'ab']. The second prints [4, 9, 16]. In the second line, repeat(2) supplies a constant second argument to pow. map stops when the shortest input, the list, runs out. This is the main use of repeat: feeding a fixed value to a function that expects an iterable.
How the three differ
| Function | Source of values | Extra memory | Can be finite |
|---|---|---|---|
| `count` | Arithmetic from start and step | Constant | No |
| `cycle` | An input iterable | Grows with input size | Only if input is empty |
| `repeat` | One object | Constant | Yes, with `times` |
Stopping safely
Never call list() on an infinite iterator. It tries to collect values forever and exhausts memory. Always bound the stream first, for example with zip against a finite input, with map over a finite input, or with islice.
Exercise
What does list(zip(cycle('xy'), [1, 2, 3, 4, 5])) return, and why does the code finish instead of running forever?
Show answer
It returns [('x', 1), ('y', 2), ('x', 3), ('y', 4), ('x', 5)]. The cycle never ends, but zip stops as soon as its shortest input, the five-item list, is exhausted.
Exercise
Write one expression that uses map, repeat and operator.mul to multiply every number in [1, 2, 3] by 10 and give the list [10, 20, 30].
Show answer
list(map(operator.mul, [1, 2, 3], repeat(10))), after from itertools import repeat and import operator.