To loop backwards in Python with a for loop, the easiest way is to use the range() function and pass ‘-1’ for the step argument.
lst = [0, 1, 2, 3]
for i in range(3, -1, -1):
print(lst[i])
#Output:
3
2
1
0
If you want to iterate over an iterable object, you can use the reversed() function.
lst = [0, 1, 2, 3]
for x in reversed(lst):
print(x)
#Output:
3
2
1
0
In programming, the ability to loop and iterate over objects is one of the fundamental concepts central to all programs.
When you are looping, by default, you do it in sequential order starting from 0 and going to some number N.
If you want to loop in reverse and go backwards, how do you do it?
To loop backwards in Python with a for loop, the easiest way is to use the range() function and pass ‘-1’ for the step argument.
For example, if you wanted to loop backwards from 100 to 0, then you would do the following.
for i in range(100, -1, -1):
do_something
If you wanted to loop backwards over a list with an index, you could do the following.
lst = [0, 1, 2, 3]
for i in range(len(lst) - 1, -1, -1):
print(lst[i])
#Output:
3
2
1
0
Using reversed() to Loop Backwards in Python
If you have an iterable object and want to loop backwards, you can use the reversed() function.
You can pass an iterable object, such as a list, to reversed() and reversed() returns the iterable object in reversed order.
Below is a simple example showing you how you can use reversed() to loop backwards in Python.
lst = [0, 1, 2, 3]
for i in range(3, -1, -1):
print(lst[i])
#Output:
3
2
1
0
Hopefully this article has been useful for you to learn how to loop with a for loop backwards in Python.