Bound Count, Cycle and Repeat
Core idea
The itertools module provides iterators that generate values on demand. count(start, step) produces arithmetic progressions, cycle(iterable) repeats a nonempty source, and repeat(value, times) yields the same object. Without a finite limit these streams can run forever. Use a fixed number of next calls or pair with a finite input.
from itertools import countfor label, number in zip(["red", "blue", "green"], count(100, 5)): print(label, number)The finite list bounds zip. The step adds five each time.
Rotate shifts
from itertools import cycleshifts = cycle(["day", "night"])print([next(shifts) for _ in range(5)])Cycle retains references to the original items for reuse; an empty input yields nothing.
Repeat one marker
from itertools import repeatmarkers = list(repeat([], 2))markers[0].append("ok")print(markers)The two positions refer to the same list, not independent copies.
Common mistake
Never call list(count()) or list(cycle(nonempty_source)). Cycle can also retain substantial memory; use it for small finite patterns.
Practice
Number four labels starting at 20 with step 3; predict the last number (29). Then create independent mutable markers with a comprehension instead of repeat.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Bound repeated streams
Check your understanding of count cycle and repeat.
What is printed?
from itertools import countc = count(3, 2)print([next(c) for _ in range(3)])What is printed?
from itertools import cycleprint(list(cycle([])))What is printed?
from itertools import repeata, b = repeat({}, 2)print(a is b)How should an unbounded count stream be consumed?