4. Looping over a collection with indices
Use enumerate when you need both the index and the element.
enumerate keeps the element and its position tied together as one iteration concept. That is less fragile than indexing into the collection manually, especially if the loop body later changes.
4.1. Don’t do this
1names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
2
3for i in range(len(names)):
4 print(i, names[i])
4.2. Do this
1names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
2
3for i, name in enumerate(names):
4 print(i, name)