CodeBlanks Logo Icon CodeBlanks

count and cycle

Learn infinite iterators with count and cycle.

count and cycle

count(start, step) produces infinitely increasing numbers; cycle(iterable) repeats an iterable forever. Both are infinite iterators; careless use leads to infinite loops.

Example: count(10, 2) produces 10, 12, 14, 16, .... cycle("AB") produces A, B, A, B, .... You must limit them with islice or zip; otherwise iteration never ends.

Using with a limit

If you write for c in count(1): on an infinite iterator, the program never stops. So you set a limit with islice or zip. zip stops when the shortest iterable ends; thanks to this, you can safely use infinite iterators.

Example: list(zip(count(1), ["a", "b"])) returns [(1, 'a'), (2, 'b')]. Since the second list has two items, count also produces two items and stops. This is a practical way for enumeration-like tasks.

Practice Use cycle and islice

Start with from itertools import cycle, islice. Create a cycle with c = cycle([1, 2]). Take the first five items with result = list(islice(c, 5)). Then print with print(result).

Starter code

main.py
# Limited iteration with cycle and islice

Sample solution

main.py
# Limited iteration with cycle and islice
from itertools import cycle, islice

c = cycle([1, 2])
result = list(islice(c, 5))
print(result)

Expected output

[1, 2, 1, 2, 1]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 count import line

Question
from itertools import count, ____

for i in zip(count(1), ["a", "b"]):
    print(i)
Answer
from itertools import count, cycle

for i in zip(count(1), ["a", "b"]):
    print(i)

Explanation: cycle is also in the itertools module.

2 When does count(1) stop?

  • Never
  • At 100
  • When some data ends
  • With a limiter Correct answer

Explanation: count stops only with a limiter like islice or zip.

3 Match the infinite iterator parts

Term Meaning
count Infinite numbers
cycle Infinite repeat
islice Limiter
zip Stops at shortest

All lessons in Intermediate