Backward iteration in Python

PythonServer Side ProgrammingProgramming

Sometimes we need to go through the elements of a list in backward order. To achieve this we need to read the last element first and then the last but one and so on till the element at index 0. Various python programming features can be used to achieve this.

Using range(N, -1, -1)

We are using the range function but starting with the position -1. This value helps us read the list from the last index value also we iterate through steps of -1. In the below example we start at a position which is measured by taking the length of the list and then taking -1 steps starting from the last position.

Example

list = ['Mon', 'Tue', 'Wed', 'Thu']
for i in range( len(list) - 1, -1, -1) :
print(list[i])

Output

Running the above code gives us the following result −

Thu
Wed
Tue
Mon

List Comprehension and [::-1]

This method involves slicing the list which starts from the position -1 and go backwards till the first position. We use a for loop with an iterator used as the index of the element in the list.

Example

list = ['Mon', 'Tue', 'Wed', 'Thu']
for i in list[::-1]:
print(i)

Output

Running the above code gives us the following result −

Thu
Wed
Tue
Mon

using reversed()

The reversed() function is very straight forward it's simply picks the elements and prints them in the reverse order.

Example

list = ['Mon', 'Tue', 'Wed', 'Thu']
for i in reversed(list) :
print(i)

Output

Running the above code gives us the following result −

Thu
Wed
Tue
Mon
Published on 07-Aug-2019 07:52:06