Member-only story
The Best Way to Loop a list “Infinitely” in Python
When working with sequences in Python, you might encounter situations where you need to loop through a list repeatedly without manually resetting the index. This is where itertools.cycle()
comes to the rescue!
Read for free: https://allwin-raju.medium.com/the-best-way-to-loop-a-list-infinitely-in-python-2d1fc040fadb?sk=1abc24e26d7ddde7712cfcc6e2d1fc7a
What is itertools.cycle()?
The cycle()
function from the itertools
module creates an iterator that continuously loops over the elements of an iterable. Once it reaches the last element, it starts again from the beginning, making it ideal for cases where infinite iteration is required.
How to Use itertools.cycle()
Using cycle()
is simple. Here’s a basic example where we cycle through a list of colours:
from itertools import cycle
colors = ["red", "green", "blue"]
color_cycle = cycle(colors)
# Print 10 elements from the cycle
for _ in range(10):
print(next(color_cycle))
Output:
red
green
blue
red
green
blue
red
green
blue
red
Practical Applications
- Round-robin scheduling — Distributing tasks cyclically among a group.