Reversing a list in python

In this article, we shall see how to reverse a list in python. There are multiple ways to do this. Let us look at one by one with an example for each. It is up to you to decide the best and efficient one.

The multiple ways to reverse a list are,

  1. reverse() method
  2. Slicing technique
  3. sort() method
  4. sorted() method

1. reverse() method

The reverse() is an inbuilt method in Python programming language that reverses objects of list in place.

The reverse() method does not return any value but 
reverse the given object from the list.

syntax

list.reverse()

Let us look at this method with an example.

reverse() method

The output of this code is,

[15, 9, 5, 4, 1]

2. Slicing technique

In this technique, a copy of the list is made and the list is not sorted in-place. Creating a copy requires more space to hold all of the existing elements. This exhausts more memory.

The original list is not sorted by this method. If you just want to print the reversed list then this method is good enough. But if you want to use the reversed list in the later part of the code, you have to assign the reversed list to some other variable.

syntax

list[start:stop:step]
list[::-1]

Let us look at this method with a code example.

reversing a list using slicing operator

3. sort() method

The next method is the sort method. We all know the sort method sorts the list in ascending order by default. It also takes an argument called reverse. This argument takes True or False, if reverse=True is given, the list is reversed.

synatx

list.sort(reverse=True)

Let us look at an example for this method.

sort() method

This method also reverses objects of list in place. So there is no need to assign the reversed list to any other variables and hence saving the memory.

The output of the above code is,

[15, 9, 5, 4, 1]

4. sorted() method

The sorted() function sorts the elements of a given iterable in a specific order (either ascending or descending) and returns the sorted iterable as a list.

syntax

sorted(list, reverse=True)

The main difference between the sort and the sorted method is that the sort method will sort the same list itself where as the sorted method will return a sorted list and hence require assigning it to a new variable.

sorted method

The output of the above program is,

[15, 9, 5, 4, 1]
[1, 4, 5, 9, 15]
[15, 9, 5, 4, 1]

Conclusion

These are the four common methods used to reverse a list. Choose the one according to your needs. For more python articles follow us regularly.

Happy coding!