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.
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.
Reverse Order By Mutating List
The simplest way to reverse the order of a list in Python use the
reverse() method in Python, however, be mindful when using this method it mutates the list and changes it permanently, as follows:
>> e = [1, 2, 3, 4, 5] >> e.reverse() >> print(e) >> [5, 4, 3, 2, 1]
Does the same apply for alphabetical lists? Yes! To reverse the alphabetical order of lists in Python would be no different from the above:
>> a = ['Apricot', 'Blueberry', 'Cherry', 'Date'] >> a.reverse() >> print(a) >> ['Date', 'Cherry', 'Blueberry', 'Apricot']
Reverse Order Without Mutating List
Another shortcut way of doing the same as the
reversed()method on lists, but without the original list being mutated is to use the slice operator
[::-1], like so:
>> a = ['Apricot', 'Blueberry', 'Cherry', 'Date'] >> b = a[::-1] >> print(a) ['Apricot', 'Blueberry', 'Cherry', 'Date'] >> print(b) ['Date', 'Cherry', 'Blueberry', 'Apricot']
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.