Cycle an iterable forever in Python
Define a generator that repeatedly yields items from an iterable, cycling back to the beginning infinitely.
Python code
14 linesdef cycle_generator(iterable):
"""Yield items from iterable forever, cycling back to the start."""
items = list(iterable) # Convert to list so it can restart
index = 0
while True:
yield items[index]
index = (index + 1) % len(items)
if __name__ == "__main__":
colors = ["red", "green", "blue"]
gen = cycle_generator(colors)
for _ in range(8):
print(next(gen), end=" ")
Output
red green blue red green blue red green
How it works
The key is converting the input iterable into a list with list(iterable) so we can restart from index 0 after reaching the end. An infinite while True loop drives the generator, and the modulo operator (index + 1) % len(items) wraps the index back to zero. Because the generator never raises StopIteration, you must control consumption externally, usually with next() or itertools.islice.
Common mistakes
- Using the original iterable directly (e.g., a generator object) which can't be replayed after exhaustion
- Forgetting modulo when len(items) is zero, causing a ZeroDivisionError
- Infinite loops in user code when no break or limit is applied
Variations
- Replace the whole function with `itertools.cycle(iterable)` from the standard library
- Use a `for` loop with `enumerate` and `next` to take a fixed number of items
Real-world use cases
- Round-robin task scheduling: cycle through worker IDs to assign jobs evenly.
- Rotating color palettes for charts or UI themes where colors repeat predictably.
- Infinite background animation payloads that alternate frames without ever ending.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.