Sub topic 3
Infinite Streams with count, cycle and repeat
This chapter covers the three infinite iterators in itertools: count, cycle and repeat. It assumes you can write functions, loops and comprehensions, and that you know what an iterator is and that one is consumed after a single pass. Generators and yield are helpful background but not required.
Why infinite iterators exist
Most iterators you meet are finite. A list, a file or a range ends, and a for loop stops with it. An infinite iterator never raises StopIteration by itself. It keeps producing values for as long as you ask.
That sounds dangerous, but it is useful for two reasons:
- You do not need to know in advance how many values you need. The consumer decides when to stop.
- Values are produced one at a time, on demand, so memory use stays constant no matter how long the stream runs.
The consumer must always supply the stopping rule. Typical rules are islice (covered in the next chapter), zip (which stops at its shortest input), break in a loop, or a function like next that takes exactly one value.
count: an endless counter
count(start=0, step=1) yields start, start + step, start + 2*step, and so on.
from itertools import count
counter = count(10, 5)
print(next(counter))
print(next(counter))
print(next(counter))This prints 10, 15 and 20. Because count is an iterator, each next call continues where the previous one stopped.
Bounding a count
The standard way to take a finite piece of an infinite stream is islice:
from itertools import count, islice
print(list(islice(count(10, 5), 4)))This prints [10, 15, 20, 25]. The islice call asks count for four values and then stops without asking for a fifth.
Steps can be negative or fractional
step may be any number, including a float or a negative value.
from itertools import count, islice
print(list(islice(count(5, -2), 4)))
print(list(islice(count(0.0, 0.5), 4)))The output is [5, 3, 1, -1] and [0.0, 0.5, 1.0, 1.5]. With floats, count computes each value by repeated addition, so rounding error can accumulate. For example, count(0, 0.1) produces values like 0.30000000000000004. If you need exact decimal steps, compute start + i * step yourself from an integer counter, or use decimal.Decimal or fractions.Fraction values.
Common uses of count
The most common use is attaching an index or an identifier to items. Pairing count with zip is a clean alternative to enumerate when you want a custom start and step:
from itertools import count
names = ['ada', 'grace', 'linus']
for ident, name in zip(count(100, 10), names):
print(ident, name)This prints 100 ada, 110 grace and 120 linus. The zip call stops when names runs out, which also stops count.
Another use is generating unique ids. A single count object shared by a function gives you a sequence that never repeats:
from itertools import count
_ids = count(1)
def new_id():
return next(_ids)
print(new_id(), new_id(), new_id())This prints 1 2 3. In CPython, next on a count object is a single C-level call, so it is effectively atomic under the GIL for ordinary integers. That is a convenient property, but do not rely on it for correctness in code that must also run on other implementations or future free-threaded builds. Use a lock when ids must be strictly unique across threads.
repeat: the same value again and again
repeat(object, times=None) yields the same object. Without times it never stops. With times it yields exactly that many copies and then ends.
from itertools import repeat
print(list(repeat('ab', 3)))This prints ['ab', 'ab', 'ab'].
repeat yields the same object, not copies
repeat does not copy. Every item is a reference to one object. For immutable values like numbers and strings this is harmless. For mutable values it is a classic trap:
from itertools import repeat
rows = list(repeat([], 3))
rows[0].append('x')
print(rows)This prints [['x'], ['x'], ['x']], because all three entries are the same list. The same problem exists with [[]] * 3. When each item must be independent, build a fresh object each time, for example with a comprehension: [[] for _ in range(3)].
The main use: a constant argument for map and zip
repeat is most useful as a constant input to functions that take several iterables. map accepts multiple iterables and stops at the shortest one, so a repeat stream can supply a fixed argument without being sized to match.
from itertools import repeat
bases = [2, 3, 4]
print(list(map(pow, bases, repeat(2))))This prints [4, 9, 16]. Each call is pow(base, 2). The infinite repeat(2) is limited by the three-item bases list.
Giving times explicitly is also a fast way to run a loop body a fixed number of times when you do not need the loop variable. It avoids creating a new integer on every pass, which makes it a small but measurable win in tight benchmarks:
from itertools import repeat
total = 0
for _ in repeat(None, 5):
total += 1
print(total)This prints 5. In ordinary code for _ in range(5) is just as clear, so prefer range unless you are measuring.
cycle: loop over a sequence forever
cycle(iterable) yields every item of the input, then starts over from the first item, forever.
from itertools import cycle, islice
print(list(islice(cycle('ABC'), 7)))This prints ['A', 'B', 'C', 'A', 'B', 'C', 'A'].
How cycle works internally
An iterator can only be read once, so cycle cannot rewind its input. Instead, during the first pass it saves a copy of every item it yields. Once the input is exhausted, it replays the saved items in order, again and again. Two consequences follow:
- Memory use is proportional to the length of the input.
cycleis not constant-memory, unlikecountandrepeat. - The input must be finite. Calling
cycle(count())never finishes its first pass, so it saves items forever and never repeats anything.
Another consequence is that cycle takes a snapshot. If you pass a list and change it later, the items already saved are unaffected once the first pass is done:
from itertools import cycle, islice
data = [1, 2]
c = cycle(data)
print(list(islice(c, 2)))
data.append(3)
print(list(islice(c, 4)))This prints [1, 2] and then [1, 2, 1, 2]. The appended 3 is never seen, because cycle finished its first pass over data before the append, and replays its saved copy afterwards. Do not rely on this timing. Treat the input as frozen once you hand it to cycle.
An empty input is a special case. cycle([]) ends immediately and yields nothing, rather than looping forever.
Typical uses of cycle
cycle is a good fit for round-robin assignment, such as alternating row colors, rotating through a pool of servers, or assigning tasks to workers in turn:
from itertools import cycle
workers = cycle(['w1', 'w2', 'w3'])
tasks = ['t1', 't2', 't3', 't4', 't5']
for task, worker in zip(tasks, workers):
print(task, '->', worker)This prints five lines, and the fourth and fifth tasks go back to w1 and w2.
A related use is repeating a short key over a longer message, as in a simple repeating-key XOR demonstration:
from itertools import cycle
message = b'HELLO WORLD'
key = b'KEY'
mixed = bytes(m ^ k for m, k in zip(message, cycle(key)))
restored = bytes(m ^ k for m, k in zip(mixed, cycle(key)))
print(restored)This prints b'HELLO WORLD'. This is only an illustration of cycle with zip. Repeating-key XOR is not real encryption.
Choosing between the three
| Function | Produces | Memory use | Stops by itself? |
|---|---|---|---|
| `count(start, step)` | An arithmetic progression of numbers | Constant | Never |
| `repeat(x)` | The same object, forever | Constant | Never |
| `repeat(x, n)` | The same object, `n` times | Constant | After `n` items |
| `cycle(it)` | The items of `it`, in order, over and over | Grows with the length of `it` | Only if `it` is empty |
How infinite streams stop
The diagram shows the usual structure: an infinite source on one side, and a consumer that decides when enough has been taken.
Common mistakes
- Materializing an infinite stream.
list(count())never returns. Always bound first. - Using
zipwith the infinite iterator first.zippulls from its inputs left to right. When the finite input ends,ziphas already taken one extra value from any iterator to its left. Put the finite iterable first if you will reuse the infinite iterator afterwards. - Expecting
repeatto copy. Mutable objects are shared, as shown above. - Expecting
cycleto see later changes to the original list, or to be constant-memory. - Accumulating float error in
count. Use integer counters and multiply when exactness matters.
The second mistake is easy to observe:
from itertools import count
c = count()
list(zip(c, 'ab'))
print(next(c))This prints 3, not 2. The zip call took 0 and 1 for the pairs, then took 2 from c before discovering that 'ab' was finished, and discarded it. Reversing the order, zip('ab', c), avoids the lost value, because zip finds the finite input exhausted before it asks c for another item.
Exercise
You want to label the lines of a list lines with the numbers 1, 3, 5, 7, ... and print each pair, without knowing how long lines is. Which itertools function do you use, and how does the loop stop? Write the loop.
Show answer
Use count(1, 2) and pair it with zip. The loop stops when lines runs out, because zip stops at its shortest input. For example: for n, line in zip(count(1, 2), lines): print(n, line). Putting lines first, as zip(lines, count(1, 2)), also works, and is the safer order if you plan to keep using the count object afterwards.
Exercise
What does this code print, and why? from itertools import cycle, islice c = cycle('xy') print(''.join(islice(c, 3))) print(''.join(islice(c, 3)))
Show answer
It prints xyx and then yxy. The cycle object is a single iterator, so the second islice continues from where the first stopped. The first call consumed x, y, x, so the next three items are y, x, y.
Exercise
Why does rows = list(repeat([], 3)) followed by rows[0].append(1) change all three rows, and how do you build three independent empty lists instead?
Show answer
repeat yields the same list object every time, so all three entries refer to one list. Appending through one entry is visible through the others. Build independent lists with a comprehension, rows = [[] for _ in range(3)], which creates a new list on each pass.