5. Looping over two collections

Avoid accessing elements by indices and manually managing which list is shorter. Use zip to iterate over both collections, stopping at the end of the shorter one.

zip makes the lockstep relationship between the iterables explicit and removes boundary arithmetic from the loop body. That generally reduces both noise and mismatch bugs.

5.1. Don’t do this

1names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
2colors = ['red', 'green', 'blue', 'orange', 'purple', 'pink']
3
4n = min(len(names), len(colors))
5for i in range(n):
6    print(names[i], colors[i])

5.2. Do this

1names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
2colors = ['red', 'green', 'blue', 'orange', 'purple', 'pink']
3
4for name, color in zip(names, colors):
5    print(name, color)