Hit enter after type your search item

How to reverse the list?

The items in a list of Python can be reversed in different ways, as described below.

The 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:

lst_reverse = [‘Banana’, ‘Mango’, ‘Straberry’, ‘Peech’]

This is how you may use the reverse method:

lst_reverse.reverse()

If you print this list, after using the reverse method, the output will be:

[‘Peech’, ‘Straberry’, ‘Mango’, ‘Banana’]

The example code and output:


The output:

list reverse

The 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:

list reverse slice

See online demo and code


 

You may learn about the slice class here.

The difference between the reverse method and slicing is, the list remains unchanged after reversing as using the second way. In the case of list reverse Python method, the list order is changed i.e. original list is reversed.

However, in 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:

Python reverse

See online demo and code


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.

reverse tuple

See online demo and code


 

Here you go, it worked for tuple as well.

This div height required for enabling the sticky sidebar