In this article we will discuss different ways to Iterate over a python list in reverse order.

Suppose we have a python list of strings i.e.

Now we want to iterate over this list in reverse order( from end to start ) i.e.

We don’t want to change the order in existing list, just want to iterate in reverse. Now let’s see how to do this using different techniques,

Iterate over the list in reverse using while loop

Get the size of list and using random and use random access operator [] to access elements in reverse i.e. from (size-1) to 0.

Iterate over the list in reverse using for loop and range()

Suppose if wordList had n elements then,

Will return list of numbers from n to 1

For example, wordList had 5 elements then above specified range() function will return,

4, 3, 2 , 1, 0

Now use that range() function in for loop and use random access operator [] to access elements in reverse i.e.

Iterate over the list using for loop and reversed()

reversed() function returns an iterator to accesses the given list in the reverse order.

Let’s iterate over that reversed sequence using for loop i.e.

It will print the wordList in reversed order.

Iterate over the list using List Comprehension and [::-1]

It will create a temporary revesed list

Let’s use this in List comprehension to iterating over the list in reverse i.e.

Iterate over the list using List Comprehension and reversed()

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.