Python Language Itertools Module Cycle through elements in an iterator

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

cycle is an infinite iterator.

>>> import itertools as it
>>> it.cycle('ABCD')
A B C D A B C D A B C D ...

Therefore, take care to give boundaries when using this to avoid an infinite loop. Example:

>>> # Iterate over each element in cycle for a fixed range
>>> cycle_iterator = it.cycle('abc123')
>>> [next(cycle_iterator) for i in range(0, 10)]
['a', 'b', 'c', '1', '2', '3', 'a', 'b', 'c', '1']


Got any Python Language Question?