ZetCode

Python infinite iterators

last modified November 30, 2026 Python 3.15

In this article we show how to work with infinite iterators in Python.

An ordinary iterator ends: after the last item, its __next__ method raises StopIteration and the for loop stops. An infinite iterator never raises StopIteration; it produces a new value every time it is asked. This works because iterators are lazy. They compute one value per request and never store the whole sequence.

The itertools module has three infinite iterators: count, cycle, and repeat. Since they never end on their own, we must always combine them with something that stops the iteration: a break statement, a finite iterable in zip, or one of the islice and takewhile functions. The iterator protocol itself is explained in Python iterators.

The count function

The count function returns an iterator of evenly spaced numbers. By default it starts at zero and goes up by one.

counter.py
from itertools import count

c = count()

print(next(c))
print(next(c))
print(next(c))

We create a counter and ask it for three values with the built-in next function. Each call returns the next number. The counter remembers its position between calls; it would keep going forever if we kept calling next.

$ python counter.py
0
1
2

Looping over count

In a for loop, an infinite iterator behaves like a while True loop with a built-in counter. The loop must end with a break.

count_loop.py
from itertools import count

for n in count(1):

    square = n * n

    if square > 50:
        break

    print(n, square)

The first argument of count is the start value, so the loop variable n goes 1, 2, 3, and so on. We do not know in advance how many numbers we need; the loop stops when the square of n exceeds 50. Without the break, the program would never end.

$ python count_loop.py
1 1
2 4
3 9
4 16
5 25
6 36
7 49

Start and step

The count(start, step) form sets the first value and the difference between consecutive values. Both may be negative or floating-point.

count_step.py
from itertools import count

tens = count(10, 10)
print(next(tens), next(tens), next(tens))

down = count(5, -1)
print(next(down), next(down), next(down))

halves = count(0.5, 0.5)
print(next(halves), next(halves), next(halves))

big = count(2 ** 64)
print(next(big))

The first counter goes up by ten, the second one counts down, and the third one produces floats. Since Python integers have no fixed size, a counter can start far beyond the 64-bit range and still produce exact values.

$ python count_step.py
10 20 30
5 4 3
0.5 1.0 1.5
18446744073709551616

Floating-point steps

With a float step, count repeatedly adds the step to the previous value. Each addition rounds the result, so the error grows with every step.

float_step.py
from itertools import count, islice

added = count(0, 0.1)
print(list(islice(added, 8, 11)))

multiplied = (i * 0.1 for i in count())
print(list(islice(multiplied, 8, 11)))

We take items 8 to 10 from two sequences that should produce 0.8, 0.9, and 1.0. The first sequence adds 0.1 ten times and accumulates the rounding error. The second one multiplies the index by the step, so each value is rounded only once. The documentation of count recommends the multiplication approach when accuracy matters. The second sequence is a generator expression, which is itself a lazy, infinite iterator here.

$ python float_step.py
[0.7999999999999999, 0.8999999999999999, 0.9999999999999999]
[0.8, 0.9, 1.0]

Numbering items with zip

The zip function stops as soon as its shortest argument is exhausted. Pairing an infinite iterator with a finite list is therefore safe; the list decides the length.

numbering.py
from itertools import count

products = ['keyboard', 'mouse', 'monitor', 'webcam']

for code, product in zip(count(1001), products):
    print(code, product)

print()

for code, product in zip(count(100, 25), products):
    print(code, product)

We give each product a code. The first loop numbers the products from 1001, the second one uses codes 100, 125, 150, and 175. For a simple step of one, the built-in enumerate(products, start=1001) does the same job; count is useful when we need a different step.

$ python numbering.py
1001 keyboard
1002 mouse
1003 monitor
1004 webcam

100 keyboard
125 mouse
150 monitor
175 webcam

Taking items with islice

The islice function slices an iterator the way the slice syntax slices a list. It accepts stop, start and stop, or start, stop, and step arguments, and returns a finite iterator.

first_items.py
from itertools import count, islice

print(list(islice(count(), 5)))
print(list(islice(count(), 5, 10)))
print(list(islice(count(), 0, 20, 4)))

evens = (n for n in count() if n % 2 == 0)
print(list(islice(evens, 6)))

The first three calls take the first five numbers, the numbers 5 to 9, and every fourth number below 20. The last example filters the counter with a generator expression first. The filter is lazy as well, so islice pulls only as many numbers through it as it needs to find six even ones. More uses of islice are shown in Python itertools.

$ python first_items.py
[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[0, 4, 8, 12, 16]
[0, 2, 4, 6, 8, 10]

Stopping on a condition

The takewhile function returns items while a predicate is true and stops at the first item for which it is false. It is the right tool when we know the condition, not the number of items.

powers.py
from itertools import count, takewhile


def below_limit(x):
    return x < 1000


powers = (2 ** n for n in count())

print(list(takewhile(below_limit, powers)))

The generator expression computes the powers of two for the numbers from count. The takewhile function stops at 1024, the first power that is not below 1000. It does not look at any later items, so the infinite sequence is not a problem.

$ python powers.py
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

The cycle function

The cycle function goes through an iterable over and over again. When it reaches the end, it starts from the first item.

colors.py
from itertools import cycle, islice

colors = cycle(['red', 'green', 'blue'])

print(next(colors))
print(next(colors))
print(next(colors))
print(next(colors))

print(list(islice(colors, 5)))

After the third color, next returns red again. The islice call then takes the next five colors; it continues where the previous calls stopped.

$ python colors.py
red
green
blue
red
['green', 'blue', 'red', 'green', 'blue']

Round-robin assignment

A common use of cycle is to distribute items evenly among a fixed set of receivers in turn.

round_robin.py
from itertools import cycle

tasks = ['backup', 'reindex', 'compress', 'mail', 'cleanup',
         'report', 'audit']
workers = ['alpha', 'beta', 'gamma']

for task, worker in zip(tasks, cycle(workers)):
    print(f'{task:<10} -> {worker}')

We have seven tasks and three workers. The zip function pairs each task with the next worker from the cycle. When the tasks run out, zip stops, and the infinite cycle is never fully used.

$ python round_robin.py
backup     -> alpha
reindex    -> beta
compress   -> gamma
mail       -> alpha
cleanup    -> beta
report     -> gamma
audit      -> alpha

cycle saves a copy

The cycle function reads its input only once. During the first pass it stores each item; the later passes are served from that saved copy. This makes it work with one-shot iterators, which cannot be restarted.

cycle_copy.py
from itertools import cycle, islice


def load(name):
    print(f'loading {name}')
    return name.upper()


names = ['ice', 'fire', 'wind']
loaded = map(load, names)

for item in islice(cycle(loaded), 7):
    print(item)

The map object is a one-shot iterator that calls the load function lazily. The output shows that each name is loaded exactly once, during the first pass. From the fourth item on, the values come from the copy stored by cycle. The copy also means that cycle needs memory for all items of its input, which matters for large inputs.

$ python cycle_copy.py
loading ice
ICE
loading fire
FIRE
loading wind
WIND
ICE
FIRE
WIND
ICE

The repeat function

The repeat function returns the same object again and again. With the second argument, times, it stops after the given number of repetitions; without it, it is infinite.

repeat_values.py
from itertools import repeat

print(list(repeat('ab', 3)))
print(''.join(repeat('-', 20)))

stars = repeat('*')
print(next(stars), next(stars), next(stars))

The first two calls are finite: they repeat a value three and twenty times. The stars iterator has no limit, so we take items from it with next. All items are the same object, not copies, which matters for mutable values such as lists.

$ python repeat_values.py
['ab', 'ab', 'ab']
--------------------
* * *

repeat with map and zip

The repeat function is most useful as a constant argument for functions that consume several iterables in parallel.

repeat_map.py
from itertools import repeat

squares = map(pow, range(8), repeat(2))
print(list(squares))

cities = ['Bratislava', 'Brno', 'Vienna']
rows = zip(cities, repeat('active'))

for row in rows:
    print(row)

The map function calls pow with one item from each iterable, so it computes pow(0, 2), pow(1, 2), and so on. In the second example, zip adds a constant status to each city. In both cases, the finite iterable determines when the iteration stops.

$ python repeat_map.py
[0, 1, 4, 9, 16, 25, 36, 49]
('Bratislava', 'active')
('Brno', 'active')
('Vienna', 'active')

A custom infinite iterator

We can write our own infinite iterator as a class with the __iter__ and __next__ methods. The __next__ method simply never raises StopIteration.

fibonacci.py
from itertools import islice


class Fibonacci:

    def __init__(self):
        self.a = 0
        self.b = 1

    def __iter__(self):
        return self

    def __next__(self):
        value = self.a
        self.a, self.b = self.b, self.a + self.b
        return value


fib = Fibonacci()

print(list(islice(fib, 10)))
print(list(islice(fib, 5)))

The Fibonacci iterator keeps the last two numbers of the sequence and computes the next one on each call. The second islice call continues where the first one stopped, because it reads from the same iterator. Generator functions offer a shorter way to write such iterators; see Python generators.

$ python fibonacci.py
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
[55, 89, 144, 233, 377]

Infinite iterators have no length

Functions that need all items of an iterable do not work on infinite iterators. Some of them raise an error, others never return.

no_length.py
from itertools import count

nums = count()

print(25 in nums)
print(next(nums))

print(len(nums))

The in operator consumes the counter until it finds 25, so the following next call returns 26. If the value were never produced, for example -1 in count(), the test would run forever. The len function fails, because iterators do not know their length. Calls such as list(nums), sum(nums), or sorted(nums) would not fail; they would hang and fill the memory.

$ python no_length.py
True
26
Traceback (most recent call last):
  File "/home/user/python/no_length.py", line 8, in <module>
    print(len(nums))
          ~~~^^^^^^
TypeError: object of type 'itertools.count' has no len()

Generating test data

The three functions work well together. In this example we combine them to generate rows of test data.

test_data.py
from itertools import count, cycle, repeat, islice

ids = count(1)
departments = cycle(['sales', 'it', 'hr'])
salaries = cycle([1800, 2100, 2400, 2700])
status = repeat('new')

records = zip(ids, departments, salaries, status)

for record in islice(records, 8):
    print(record)

print(next(records))

Each column comes from an infinite iterator: count gives unique IDs, the two cycle calls rotate through departments and salaries, and repeat fills in a constant status. Since the department and salary lists have different lengths, the combinations do not repeat every three rows. The zip object is infinite as well, so islice takes eight records. The records iterator is not exhausted afterwards; the last line asks it for one more record.

$ python test_data.py
(1, 'sales', 1800, 'new')
(2, 'it', 2100, 'new')
(3, 'hr', 2400, 'new')
(4, 'sales', 2700, 'new')
(5, 'it', 1800, 'new')
(6, 'hr', 2100, 'new')
(7, 'sales', 2400, 'new')
(8, 'it', 2700, 'new')
(9, 'hr', 1800, 'new')

Source

itertools – Functions creating iterators for efficient looping, Iterator types

In this article we have worked with the infinite iterators count, cycle, and repeat, stopped them with break, zip, islice, and takewhile, and written a custom infinite iterator class. See also Python iterators, Python generators, Python chain, and Python itertools.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.