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.
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.
list = ['Mon', 'Tue', 'Wed', 'Thu'] for i in range( len(list) - 1, -1, -1) : print(list[i])
Running the above code gives us the following result −
Thu Wed Tue Mon
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.
list = ['Mon', 'Tue', 'Wed', 'Thu'] for i in list[::-1]: print(i)
Running the above code gives us the following result −
Thu Wed Tue Mon
The reversed() function is very straight forward it's simply picks the elements and prints them in the reverse order.
list = ['Mon', 'Tue', 'Wed', 'Thu'] for i in reversed(list) : print(i)
Running the above code gives us the following result −
Thu Wed Tue Mon