How to Cycle Through a List Infinitely with itertools

This code uses itertools.cycle to create an infinite iterator over a list and returns the first n items from that cycle.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

17 lines
Python 3.9+
from itertools import cycle

def demonstrate_cycle(items, cycles=3):
    """
    Cycle through a list infinitely using itertools.cycle.
    Returns the first n items from the infinite cycle.
    """
    cycled = cycle(items)
    result = [next(cycled) for _ in range(len(items) * cycles)]
    return result

if __name__ == "__main__":
    fruits = ["apple", "banana", "orange"]
    output = demonstrate_cycle(fruits, cycles=2)
    print("Original list:", fruits)
    print("Cycled output (2 full rounds):", output)
    print("Joined output:", " -> ".join(output))

Output

stdout
Original list: ['apple', 'banana', 'orange']
Cycled output (2 full rounds): ['apple', 'banana', 'orange', 'apple', 'banana', 'orange']
Joined output: apple -> banana -> orange -> apple -> banana -> orange

How it works

The itertools.cycle function creates an iterator that yields items from the input iterable repeatedly, forever. When you call next(cycled), it returns the next item in the cycle, wrapping back to the beginning after reaching the end. This code uses a list comprehension to pull exactly len(items) * cycles items, giving you a finite number of items from the infinite sequence. The result is a list that repeats the original items cycles times in order.

Common mistakes

  • Trying to convert `cycle` directly to a list, which would cause an infinite loop.
  • Forgetting that `cycle` requires an iterable argument; passing a single item won't cycle correctly.
  • Not using `next()` to retrieve items, leading to confusion with the iterator object itself.

Variations

  1. Use `islice(cycle(items), n)` to take the first n items without building a list comprehension.
  2. Use a `while` loop with `next()` to process items one at a time until a condition is met.

Real-world use cases

  • Round-robin scheduling of workers or servers in a load balancer.
  • Repeating a list of tasks or notifications in a loop until stopped.
  • Cycling through colors or styles in a UI component for iterative updates.

Sponsored

Run this sample

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

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.