How to Use itertools.cycle in Python: Simple Guide
Use
itertools.cycle(iterable) to create an iterator that repeats the elements of iterable endlessly. It cycles through the items one by one and starts over when it reaches the end.Syntax
The syntax for itertools.cycle is simple:
itertools.cycle(iterable): Takes any iterable (like a list, tuple, or string).- Returns an iterator that repeats the elements of the iterable forever.
python
import itertools cycler = itertools.cycle(['A', 'B', 'C'])
Example
This example shows how to use itertools.cycle to print the first 10 elements cycling through a list of letters.
python
import itertools cycler = itertools.cycle(['A', 'B', 'C']) for _ in range(10): print(next(cycler), end=' ')
Output
A B C A B C A B C A
Common Pitfalls
One common mistake is to forget that cycle never ends on its own. If you use it in a loop without a stopping condition, your program will run forever.
Also, if the original iterable is empty, cycle will raise StopIteration immediately when you try to get the next item.
python
import itertools # Wrong: infinite loop without break # cycler = itertools.cycle([1, 2, 3]) # while True: # print(next(cycler)) # This will never stop # Right: use a limit cycler = itertools.cycle([1, 2, 3]) for _ in range(6): print(next(cycler), end=' ')
Output
1 2 3 1 2 3
Quick Reference
| Function | Description |
|---|---|
| itertools.cycle(iterable) | Creates an iterator that repeats elements of iterable endlessly |
| next(iterator) | Gets the next element from the cycle |
| Use with a loop and a limit | Avoid infinite loops by controlling iterations |
Key Takeaways
Use itertools.cycle to repeat elements endlessly from any iterable.
Always control the number of iterations to avoid infinite loops.
cycle raises StopIteration immediately if the iterable is empty.
Use next() to get the next item from the cycle iterator.
cycle is useful for repeating patterns without manually resetting.