42. Cycling through a list

Here’s how to cycle through a list of elements an arbitrary number of times.

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

42.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))