How to Iterate Over Lists and Strings in Reverse Order in Python
This guide explores various methods for iterating over lists and strings in reverse order in Python. We'll cover using the reversed()
function, negative step slicing, and how to get both the index and value while iterating in reverse.
Iterating Over Lists in Reverse
Using reversed()
The reversed()
function is the most Pythonic and efficient way to iterate over a list in reverse order. It returns a reverse iterator, which you can loop over directly:
my_list = ['a', 'b', 'c', 'd']
for item in reversed(my_list):
print(item) # Output: d c b a
- The
reversed()
function returns an iterator and is generally more memory efficient. - The original list
my_list
remains unchanged.
Using Negative Step Slicing
Negative step slicing provides a concise way to create a reversed copy of a list, which you can then iterate over:
my_list = ['a', 'b', 'c', 'd']
for item in my_list[::-1]:
print(item) # Output: d c b a
[::-1]
creates a new, reversed list. The originalmy_list
is not modified.- This is less efficient than
reversed()
as it requires extra memory.
Reverse iteration with index
To iterate in reverse while keeping track of the original index use the enumerate
method, cast the result to a list, and reverse the list using reversed()
.
my_list = ['a', 'b', 'c', 'd']
for index, item in reversed(list(enumerate(my_list))):
print(index, item) # Output: 3 d 2 c 1 b 0 a
Iterating Over Strings in Reverse
Using reversed()
The reversed()
function will also work on strings.
my_str = 'abcd'
for char in reversed(my_str):
print(char) # Output: d c b a
Using Negative Step Slicing
You can reverse the string before iterating over it:
my_str = 'abcd'
for char in my_str[::-1]:
print(char) # Output: d c b a
Reverse iteration with index
To iterate in reverse while keeping track of the original index use the enumerate
method, cast the result to a list, and reverse the list using reversed()
.
my_str = 'abcd'
for index, char in reversed(list(enumerate(my_str))):
print(index, char) # Output: 3 d 2 c 1 b 0 a
Conclusion
This guide provided multiple methods for reverse iteration in Python.
- The
reversed()
function is the most readable and should be preferred when you don't need to create a copy of the object you are reversing. - Negative step slicing creates a reversed copy, which is useful if you want to keep the original order, but requires extra memory.
You also learned how to get the index and value while iterating in reverse order.