There have been times when after creating a list in Python I’ve wanted to sort a list and then have the list reversed from ascending to descending.
To reverse the order of a list in Python use either the
.reverse() list method which mutates the original list, or the slice operator technique
[::-1] which returns a new list.
What are the quickest ways to get this task done? Here are two ways to do the same thing, but one method will mutate the original list when operated, whereas the other outputs a new list and keeps the original list as it originally was.
What Does The List Method
The simplest way to reverse the order of a list in Python is to use the
reverse() list method in Python, however, be mindful when using this method it mutates the list and changes the original list.
Here is an example of how the
.reverse() list method works:
>> e = [1, 2, 3, 4, 5] >> e.reverse() >> print(e) >> [5, 4, 3, 2, 1] >> a = ['Apricot', 'Blueberry', 'Cherry', 'Date'] >> a.reverse() >> print(a) >> ['Date', 'Cherry', 'Blueberry', 'Apricot']
Notice once the call to reverse has been applied on the list the state of the original list changes. This is a mutation and you may want to avoid this as it can make it difficult to debug Python scripts when variables are mutated.
If you want to avoid mutating your original list then you might want to use the slice operator instead.
A great way of being able to reverse a list in Python is to perform a
slice operation as this allows you to keep the original list without mutating it.
An example of using the slice operator is as follows:
>> a = ['Apricot', 'Blueberry', 'Cherry', 'Date'] >> b = a[::-1] >> print(a) ['Apricot', 'Blueberry', 'Cherry', 'Date'] >> print(b) ['Date', 'Cherry', 'Blueberry', 'Apricot']
The way the slice operator works is as follows:
- The first item represents which item to start at. If nothing is there, it uses the start.
- The second item represents which item to end at – exclusively. In other words it doesn’t include this item.
- And finally the last item in the operator is the step count. If nothing is used it assumes a step of
-1would assume going backwards.
Therefore, the slice operator of
[::-1] would mean, start at the beginning go to the very end, and then go backwards.
I prefer this method as I still have access to the original variable’s list in case I need to perform other operations on the original list.
Without using a for loop we can easily reverse the order of a list in Python, it just matters whether you want to mutate the original list, or keep the original list in place and want a copy of the new list as a new list.