GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Python Infinite Iterators - Complete Guide Python Infinite IteratorsLast modified March 29, 2025 This detailed guide delves into Python's infinite iterators, which are special objects capable of generating values endlessly without triggering a StopIteration exception. We will explore the built-in itertools module functions and demonstrate custom implementations with clear, practical examples. Understanding Infinite IteratorsInfinite iterators are unique objects that yield values indefinitely when iterated over. In contrast to finite iterators, which stop after exhausting their elements, infinite iterators persist in producing values until manually halted. basic_infinite.py
def count_up():
n = 0
while True:
yield n
n += 1
counter = count_up()
print(next(counter)) # 0
print(next(counter)) # 1
# Continues infinitely
The itertools.count
The itertools_count.py
from itertools import count # Basic count starting from 0 counter = count() print(next(counter)) # 0 print(next(counter)) # 1 # Count with custom start and step decimal_counter = count(start=1.0, step=0.25) print(next(decimal_counter)) # 1.0 print(next(decimal_counter)) # 1.25
The itertools.cycle
The itertools_cycle.py
from itertools import cycle seasons = cycle(['spring', 'summer', 'fall', 'winter']) print(next(seasons)) # spring print(next(seasons)) # summer print(next(seasons)) # fall print(next(seasons)) # winter print(next(seasons)) # spring This iterator operates by accepting an iterable like a list or tuple, storing its elements in a buffer, yielding them sequentially, and restarting from the beginning upon completion. It remains memory-efficient for large iterables, supports any iterable type, and preserves the original order accurately. itertools.repeat
The itertools_repeat.py
from itertools import repeat
# Infinite repetition
greeting = repeat('hello')
print(next(greeting)) # hello
print(next(greeting)) # hello
# Finite repetition
three_hi = repeat('hi', 3)
print(list(three_hi)) # ['hi', 'hi', 'hi']
The Custom Infinite Iterator ClassYou can design custom infinite iterators by implementing Python's iterator protocol, tailoring behavior to specific needs. custom_iterator.py
class Squares:
def __iter__(self):
self.n = 1
return self
def __next__(self):
result = self.n * self.n
self.n += 1
return result
squares = Squares()
sq_iter = iter(squares)
print(next(sq_iter)) # 1
print(next(sq_iter)) # 4
print(next(sq_iter)) # 9
print(next(sq_iter)) # 16
The Infinite Random Data GeneratorInfinite iterators shine when producing continuous streams of random data, ideal for testing or simulation scenarios. random_data.py
import random
import itertools
def random_chars():
while True:
yield chr(random.randint(65, 90))
# Create infinite random character stream
chars = random_chars()
# Take 5 samples
first_five = itertools.islice(chars, 5)
print(list(first_five)) # e.g., ['K', 'P', 'M', 'T', 'B']
This example features an infinite generator producing random uppercase
letters, paired with Chaining Infinite Iterators
The chaining_iterators.py
from itertools import chain, count, repeat
# Chain multiple iterators
combo = chain(
count(5, 5), # 5, 10, 15...
repeat('X', 2), # X, X
count(50, -10) # 50, 40, 30...
)
print(next(combo)) # 5
print(next(combo)) # 10
print(next(combo)) # 15
print(next(combo)) # X
print(next(combo)) # X
print(next(combo)) # 50
The Controlling Infinite Iteration
Although infinite iterators run indefinitely, tools like
controlled_iteration.py
from itertools import count, islice # Infinite counter nums = count(0) # Take first 5 multiples of 3 threes = (x for x in nums if x % 3 == 0) first_five_threes = islice(threes, 5) print(list(first_five_threes)) # [0, 3, 6, 9, 12]
This example demonstrates control with Memory Efficiency ConsiderationsInfinite iterators excel in memory efficiency by producing values on demand rather than storing entire sequences upfront. memory_efficiency.py
import sys
from itertools import count
# Infinite iterator
infinite = count()
# Regular list would fail
try:
infinite_list = list(range(sys.maxsize + 1))
except MemoryError:
print("Cannot create infinite list!")
# Iterator works fine
print(next(infinite)) # 0
print(next(infinite)) # 1
These iterators generate one value at a time, avoid precomputing full sequences, handle data beyond memory limits, and support lazy evaluation. They are perfect for large datasets, streaming pipelines, constrained environments, or prolonged operations. Best Practices
Source ReferencesAuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Python tutorials. |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |