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
Backward iteration in Python
Sometimes we need to iterate through a list in reverse order − reading the last element first, then the second-to-last, and so on. Python provides three common approaches: range() with negative step, slice notation [::-1], and the reversed() built-in function.
Using range() with Negative Step
Start from the last index and step backwards by -1 until index 0 ?
days = ['Mon', 'Tue', 'Wed', 'Thu']
for i in range(len(days) - 1, -1, -1):
print(days[i])
Thu Wed Tue Mon
range(3, -1, -1) generates indices 3, 2, 1, 0. This gives you access to the index, which is useful when you need both the position and the value.
Using Slice [::-1]
Slice notation creates a reversed copy of the list and iterates over it ?
days = ['Mon', 'Tue', 'Wed', 'Thu']
for item in days[::-1]:
print(item)
Thu Wed Tue Mon
[::-1] means start from the end, go to the beginning, stepping -1. This creates a new reversed list in memory.
Using reversed()
The reversed() built-in returns a reverse iterator without creating a copy ?
days = ['Mon', 'Tue', 'Wed', 'Thu']
for item in reversed(days):
print(item)
Thu Wed Tue Mon
reversed() is memory-efficient because it returns an iterator that traverses the original list backwards without creating a new list.
Comparison
| Method | Syntax | Creates Copy? | Access to Index? | Best For |
|---|---|---|---|---|
range() |
range(len(a)-1, -1, -1) |
No | Yes | When you need the index |
[::-1] |
for x in a[::-1] |
Yes (new list) | No | Short, readable syntax |
reversed() |
for x in reversed(a) |
No (iterator) | No | Memory-efficient, clean |
Conclusion
Use reversed() for the most Pythonic and memory-efficient backward iteration. Use [::-1] for short, readable code when a copy is acceptable. Use range() with a negative step when you need access to the index during iteration.
