How to Iterate Through a List in Reverse in Python



Python


In this article, we show how to iterate through a list in reverse in Python.

So, in Python, we are not limited to going through a list in the forward sequence. We can also go through the list in reverse (from the last item to the first item).

We do this using the reversed() function in Python. This function allows us to reverse all elements in the list.

We then use the for loop to print out each element of the list.

This is shown in the following code below.



So let's now go through our code.

So we have our first list, named list1, which contains the numbers, [1,2,3,4]

We then create another variable, reverselist1, and set this equal to reversed(list1). This reverses all elements in the list so that the list starts from the last items and works it way forward from the end.

We then create another the, list2, which contains 4 items, ['first', 'second', 'third', 'fourth']

We then create another variable, reverselist2, and set it equal to reversed(list), which reverses the elements.

You can see now how the elements go from back to front.

We then create one more variable, list3, which has the elements, [1,2,3,4,5,6]

This time, we don't create a separate variable to store the reversed list.

Instead we use the reversed() function in the for loop to loop through the list in reverse.

So it's not necessary to create another variable if you simply want to print out each element in reverse. If you want to store the elements in reverse in your program, then it would be necessary to create another variable.

And this is how to iterate through a list in reverse in Python.


Related Resources

How to Show All Tables of a MySQL Database in Python

How to Count the Number of Rows in a MySQL Table in Python



HTML Comment Box is loading comments...