Skip to content

How to Create Infinite Iterators in Python

Learn how to build memory-efficient infinite iterators in Python using generator functions and the itertools module for unbounded sequences like counters, cycles, and Fibonacci series.

An infinite iterator is a data stream that never ends. Unlike standard lists or tuples, which store all elements in memory, infinite iterators generate values on the fly. This makes them incredibly memory-efficient for representing unbounded sequences, such as mathematical series, sensor data streams, or repetitive cycling patterns.

This guide explores how to build infinite iterators using generator functions and the built-in itertools module.

Understanding Infinite Iterators

Standard iterables (like lists) have a fixed length. Infinite iterators do not; they theoretically run forever until you explicitly stop requesting the next item.

They rely on Lazy Evaluation: values are computed only when needed, not beforehand. This allows you to represent an infinite sequence like the Fibonacci series without crashing your computer's memory.

Method 1: Using Generator Functions (Custom Logic)

The most flexible way to create an infinite sequence is using a Python generator function. A generator uses the yield keyword to return a value and pause execution until the next value is requested.

To make it infinite, simply place the yield statement inside a while True loop.

def infinite_counter(start=0):
    current = start
    while True:
        yield current
        current += 1

counter = infinite_counter(10)

print(next(counter))
print(next(counter))
print(next(counter))

Output:

10
11
12

Example: Infinite Fibonacci Sequence

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()

for _ in range(5):
    print(next(fib))

Output:

0
1
1
2
3

Method 2: Using the itertools Module (Standard Library)

Python's itertools module provides optimized, built-in functions for common infinite patterns.

itertools.count(start, step)

Counts infinitely from a starting number.

from itertools import count

even_counter = count(10, 2)

print(next(even_counter))  # 10
print(next(even_counter))  # 12
print(next(even_counter))  # 14

itertools.cycle(iterable)

Repeats a sequence infinitely (A, B, C, A, B, C...).

from itertools import cycle

colors = cycle(['Red', 'Green', 'Blue'])

print(next(colors))  # Red
print(next(colors))  # Green
print(next(colors))  # Blue
print(next(colors))  # Red (Cycle restarts)

itertools.repeat(elem, times)

Repeats a specific element infinitely (or a specific number of times).

from itertools import repeat

greeter = repeat("Hello")

print(next(greeter)) # Hello
print(next(greeter)) # Hello

Controlling Infinite Loops (Safety)

You must use slicing or conditional logic to consume only a finite portion of the infinite stream.

islice allows you to take a "slice" of an infinite iterator safely.

from itertools import count, islice

counter = count(0)

limited_items = list(islice(counter, 5))

print(limited_items)

Output:

[0, 1, 2, 3, 4]

Using break in loops

counter = count(0)

for num in counter:
    if num > 4:
        break  # ✅ Correct: Manual exit condition
    print(num)

Conclusion

Infinite iterators are powerful tools for processing streams of data and generating sequences without memory overhead.

  1. Use Generator Functions (yield + while True) for custom logic sequences.
  2. Use itertools (count, cycle, repeat) for standard patterns.
  3. Always Limit Consumption using islice or break to prevent infinite loops from freezing your program.
Navigation