For a feature I build I needed a simple way to reverse the direction the for-statement iterates through a list. As it turns out, Python has a built-in function called reversed() that does exactly that.
This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.
Iterate forward
When we iterate over a list, the iterator gives us the elements in the same order as we inserted them into the list:
1 2 3 |
numbers = [1, 2, 3, 4, 5] for x in numbers: print(x) |
1
2
3
4
5
We could change this behaviour by creating our own iterator. While this may be necessary with a complex requirement, it is not needed to change the direction of the iterator.
Iterate backwards
The built-in function reversed() changes the direction of the iterator without changing the underlying data:
1 2 3 4 5 6 |
numbers = [1, 2, 3, 4, 5] for x in reversed(numbers): print(x) print(numbers) |
5
4
3
2
1
[1, 2, 3, 4, 5]
Conclusion
If you need to run in the opposite direction through an iteratable (like a list), reversed() is the function that does exactly what you need.