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.
Python code
17 linesfrom 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
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
- Use `islice(cycle(items), n)` to take the first n items without building a list comprehension.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.