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,
- reverse() method
- Slicing technique
- sort() method
- 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.
Let us look at this method with an example.
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.
Let us look at this method with a code example.
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.
Let us look at an example for this 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.
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.
The output of the above program is,
[15, 9, 5, 4, 1] [1, 4, 5, 9, 15] [15, 9, 5, 4, 1]
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.