2. Looping backward
Avoid awkward -1 bounds when iterating backward. Use reversed to make the code clearer.
reversed states the direction change without exposing the indexing mechanics needed to accomplish it. That makes the loop easier to inspect and less error-prone when the sequence bounds change.
2.1. Don’t do this
1names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
2
3for i in range(len(names) - 1, -1, -1):
4 print(names[i])
2.2. Do this
1names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
2
3for name in reversed(names):
4 print(name)