10.9. Iterator Cycle

  • itertools.cycle(iterable)

10.9.1. Solution

>>> from itertools import cycle
>>>
>>>
>>> data = cycle(['white', 'gray'])
>>>
>>> next(data)
'white'
>>> next(data)
'gray'
>>> next(data)
'white'
>>> next(data)
'gray'

10.9.2. Iteration

>>> names = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>> colors = cycle(['white', 'gray'])
>>>
>>> for name, color in zip(names, colors):
...     print(color, name)
...
white Alice
gray Bob
white Carol
gray Dave
white Eve
gray Mallory

10.9.3. Example

>>> from itertools import cycle
>>>
>>>
>>> for i, status in enumerate(cycle(['even', 'odd'])):  # doctest + SKIP
...     print(i, status)
...     if i == 3:
...         break
0 even
1 odd
2 even
3 odd

10.9.4. Use Case - 1

>>> servers = cycle([
...     '192.168.0.10',
...     '192.168.0.11',
...     '192.168.0.12',
...     '192.168.0.13',
... ])
>>> next(servers)
'192.168.0.10'
>>>
>>> next(servers)
'192.168.0.11'
>>>
>>> next(servers)
'192.168.0.12'
>>>
>>> next(servers)
'192.168.0.13'
>>>
>>> next(servers)
'192.168.0.10'
>>>
>>> next(servers)
'192.168.0.11'
>>>
>>> next(servers)
'192.168.0.12'
>>>
>>> next(servers)
'192.168.0.13'
>>>
>>> next(servers)
'192.168.0.10'
>>>