Traverse a list in reverse order in Python
This post will discuss how to traverse a list in reverse order in Python without modifying the original list.
1. Using built-in reversed() function
You can pass the list to the built-in function reversed(), which returns a reverse iterator and doesn’t modify the list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5] for x in reversed(a): print(x) ''' Output: 5 4 3 2 1 ''' |
If you need the indices, use the enumerate() function for getting the position index and corresponding value.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5] for i, v in reversed(list(enumerate(a))): print(i, v) ''' Output: 4 5 3 4 2 3 1 2 0 1 ''' |
Another way to iterate with indices can be done in the following manner:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5] for i in range(len(a) - 1, -1, -1): print(i, a[i]) ''' Output: 4 5 3 4 2 3 1 2 0 1 ''' |
2. Using extended slicing
The [::-1] slice makes a copy of the list in reverse order, which can be used in the for-loop to print items in reverse order.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5] for x in a[::-1]: print(x) ''' Output: 5 4 3 2 1 ''' |
That’s all about traversing a list in reverse order in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)