Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I iterate over a sequence in reverse order in Python?
Python provides several effective methods to iterate over sequences in reverse order. Whether you're working with lists, tuples, or strings, you can choose from multiple approaches depending on your specific needs and coding style.
Using While Loop
The while loop approach manually controls the iteration by starting from the last index and decrementing until reaching the first element ?
# Creating a List
names = ["Jacob", "Harry", "Mark", "Anthony"]
# Displaying the List
print("List =", names)
# Length - 1
i = len(names) - 1
# Iterate in reverse order
print("Display the List in Reverse order:")
while i >= 0:
print(names[i])
i -= 1
List = ['Jacob', 'Harry', 'Mark', 'Anthony'] Display the List in Reverse order: Anthony Mark Harry Jacob
Using range() with Negative Step
The range() function with negative step provides a cleaner approach when you need access to indices ?
# Creating a List
names = ["Jacob", "Harry", "Mark", "Anthony"]
# Displaying the List
print("List =", names)
# Iterate in reverse order using range()
print("Display the List in Reverse order:")
for i in range(len(names) - 1, -1, -1):
print(names[i])
List = ['Jacob', 'Harry', 'Mark', 'Anthony'] Display the List in Reverse order: Anthony Mark Harry Jacob
Using reversed() Function
The reversed() function returns a reverse iterator, making it the most memory-efficient option for large sequences ?
# Creating a List
names = ["Jacob", "Harry", "Mark", "Anthony"]
# Displaying the List
print("List =", names)
# Iterate in reverse order using reversed()
print("Display the List in Reverse order:")
for item in reversed(names):
print(item)
List = ['Jacob', 'Harry', 'Mark', 'Anthony'] Display the List in Reverse order: Anthony Mark Harry Jacob
Using Slice with Negative Step
Slicing with [::-1] creates a reversed copy of the sequence, offering the most concise syntax ?
# Creating a List
names = ["Jacob", "Harry", "Mark", "Anthony"]
# Displaying the List
print("List =", names)
# Iterate in reverse order using slice
print("Display the List in Reverse order:")
for item in names[::-1]:
print(item)
List = ['Jacob', 'Harry', 'Mark', 'Anthony'] Display the List in Reverse order: Anthony Mark Harry Jacob
Comparison
| Method | Creates Copy? | Memory Usage | Best For |
|---|---|---|---|
while loop |
No | Low | Manual control needed |
range() |
No | Low | When you need indices |
reversed() |
No (iterator) | Very Low | Large sequences |
[::-1] slice |
Yes | High | Short, readable code |
Conclusion
Use reversed() for memory-efficient iteration over large sequences. Choose [::-1] for short, readable code when memory isn't a concern. Use range() with negative step when you need access to indices during iteration.
