In this tutorial, we will learn how to iterate over a list in reverse order. For example, if we have a list [1,2,3,4,5], we will traverse it in the order 5->4->3->2->1. We have different ways to traverse a list in reverse order.
The iteration will not change the order of the list and we will not do any modifications to the list elements. I will show you different ways to achieve this. Let’s take a look :
Iterate over the list in reverse using ‘for’ loop :
loop helps us always while iterating through something. In python, we have range() function to iterate. We can define this method as range([start], stop[, step]).
-
start: It is the starting index of the sequence.
-
stop: The range will run till this index, but it will not include this index.
-
step: Difference between each element of the sequence.
So, in our case, the start will be the index of the last element of the list, stop will be 0 i.e. first element of the list, and step will be -1 since we are decrementing the index by 1 on each step.
The program will look as like below :
#1
my_list = [1,2,3,4,5,6]
#2
for i in range(len(my_list) - 1,-1,-1) :
print(my_list[i])
Explanation :
The commented numbers in the above program denote the step number below:
-
my_list is the list we are using in this program.
-
This for loop will run from the index of the last element of the list to the 0th index element of the list. The print statement inside the loop will print out the values.
Output:
Using a while loop :
Similar to a for loop, we can also use while loop to iterate a list in reverse.
#1
my_list = [1,2,3,4,5,6]
#2
list_length = len(my_list)
#3
index = list_length - 1
#4
while index >= 0 :
print(my_list[index])
index -= 1
Explanation :
The commented numbers in the above program denote the step number below:
-
We are using the same list as the above example.
-
First, we have calculated the length of the list using the len() method.
-
index variable is initialized with value length of the list - 1. It is used to indicate the current index of the list while iterating.
-
This loop will run until the value of index becomes 0. Each time, index value is decremented by 1. The print line will print out the current iterating value of the list.
It will print the following output :
As you can see, the result is the same as above.
Using [::-1], the simplest way to reverse a list :
We can also reverse a list using only one line like below :
my_list = [1,2,3,4,5,6]
reverse_list = my_list[::-1]
print(reverse_list)
my_list[::-1] creates a reversed list and store it in the reverse_list variable. It will print the below output :
Conclusion :
We have learned three different ways to reverse a list in python. You can use any one of the methods above but the third one is the easiest one. Try the examples above and drop a comment below if you find any problem.
The source code for the above examples are available here.