How to Create Infinite Iterators in Python
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 the current value and pause here
yield current
current += 1
# Initialize the iterator
counter = infinite_counter(10)
# ✅ Correct: Fetch values one by one using next()
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()
# Fetch the first 5 Fibonacci numbers
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
# Start at 10, increment by 2
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
# Repeat "Hello" infinitely
greeter = repeat("Hello")
print(next(greeter)) # Hello
print(next(greeter)) # Hello
Controlling Infinite Loops (Safety)
Warning: If you loop over an infinite iterator using for item in iterator: without a break condition, your program will run forever (or hang).
You must use slicing or conditional logic to consume only a finite portion of the infinite stream.
Using itertools.islice (Recommended)
islice allows you to take a "slice" of an infinite iterator safely.
from itertools import count, islice
counter = count(0)
# ✅ Correct: Take the next 5 items safely
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.
- Use Generator Functions (
yield+while True) for custom logic sequences. - Use
itertools(count,cycle,repeat) for standard patterns. - Always Limit Consumption using
isliceorbreakto prevent infinite loops from freezing your program.