9.11. Iterator Cycle

  • itertools.cycle(iterable)

9.11.1. Solution

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

9.11.2. 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

9.11.3. 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'
>>>