The items in a list of Python can be reversed in different ways, as described below.
First way – using the reverse method of the list
You may reverse a list by using the Python reverse list method. For example, we have the following list:
This is how you may use the reverse method:
If you print this list, after using the reverse method, the output will be:
The example code and output:
#A Demo reversing list items lst_reverse = ['Banana', 'Mango', 'Straberry', 'Peech'] print ("The list before reverse method:",lst_reverse) lst_reverse.reverse() print ("List after reverse method:",lst_reverse)
The output:
List after reverse method: [‘Peech’, ‘Strawberry’, ‘Mango’, ‘Banana’]
Second way of reversing the list items – Slice
The second way is a trick that applies to other iterables in Python. This way is extended slice; see an example below.
In this example, a list of four fruit names is created. After that, the extended slice trick is used where default values for start and stop (None) are given while -1 for the step is used. See this working:
#A Demo reversing list items lst_reverse = ['Banana', 'Mango', 'Strawberry', 'Peech'] print ("The list before slice:",lst_reverse) print ("List after slice:",lst_reverse[::-1])
Output:
List after slice: [‘Peech’, ‘Strawberry’, ‘Mango’, ‘Banana’]
You may learn about the slice class here.
The difference between the reverse method and slicing is that the list remains unchanged after reversing as using the second way.
In the case of the Python list reverse method, the list order is changed i.e. original list is reversed. However, in the case of slicing, the original list remains the same.
See the following code and output below where I displayed the original list after using the slicing:
#A Demo reversing list items lst_reverse =['Banana', 'Mango', 'Straberry', 'Peech'] print ("The list before slice:",lst_reverse) print ("List after slice:",lst_reverse[::-1]) print ("The original list after slice:",lst_reverse)
Result:
List after slice: [‘Peech’, ‘Strawberry’, ‘Mango’, ‘Banana’]
The original list after slice: [‘Banana’, ‘Mango’, ‘Strawberry’, ‘Peech’]
You can see, the list retains the same order as before slicing.
Using slicing trick to reverse tuple
As mentioned earlier, the reverse method is specific to the list. What if you need to reverse a tuple? As such, a tuple is immutable i.e. once created it cannot be changed so this trick of using slice will work for tuple as well, as this does not change actual iterable.
#A Demo reversing a tuple tuple_reverse = [5, 10, 15, 20, 25] print ("The tuple before slice:",tuple_reverse) print ("Tuple after slice:",tuple_reverse[::-1])
Output:
Tuple after slice: [25, 20, 15, 10, 5]
Here you go, it worked for Tuple as well.