11. Cycling through a list
Here is how to cycle through a list of elements an arbitrary number of times.
itertools.cycle makes the potentially unbounded nature of the iteration explicit. That is easier to reason about than manually wrapping an index back to zero every time you hit the end.
11.1. Don’t do this
1colors = ['red', 'green', 'blue']
2
3color_sequence = []
4index = 0
5
6for i in range(10):
7 color_sequence.append(colors[index])
8 index += 1
9 if index == 3:
10 index = 0
11.2. Do this
1from itertools import cycle
2
3colors = ['red', 'green', 'blue']
4
5color_cycle = cycle(colors)
6color_sequence = (next(color_cycle) for _ in range(10))