Cycle an iterable forever in Python

Define a generator that repeatedly yields items from an iterable, cycling back to the beginning infinitely.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 14 views 0 copies

Python code

14 lines
Python 3.9+
def 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

stdout
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

  1. Replace the whole function with `itertools.cycle(iterable)` from the standard library
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.