9. Looping over two collections
The key is to avoid accessing elements by indicies and also managing the concern of which list is smaller than which. Use zip to iterate over the two lists; the iteration will only go until the end of the shorter list.
9.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])
9.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)