Python list reverse: How To Reverse List In Python
Python List reverse() is an inbuilt function that reverses the sorting order of the items. The reverse() function doesn’t return any value. It takes no parameters. It only reverses the elements and updates the list. List reverse() reverses objects of the list in place.
Python List Reverse Example
Reversing a list is a standard operation in Python programming.
For example, imagine you had the sorted list of the employee names that your code displays in alphabetical (A-Z) order.
Some of your users would like to view the employee list so that the names are in the reverse alphabetical order. How are you going to flip the order of this existing list on its head?
In this article you’ll see three different ways to achieve this result in “plain vanilla” Python, meaning without the use of any third-party Python libraries:
- Reversing the list in-place with a Python list.reverse() method.
- Using the “[::-1]” list slicing technique to create a reversed copy.
- Creating a reverse iterator with a reversed() built-in function.
Let’s start with the list.reverse() function in Python.
The syntax of the Python list reverse() method is the following.
The simple example is the following.
# app.py GoT = ['Jon', 'Tyrion', 'Daenerys'] GoT.reverse() print (GoT)
See the output.
One thing here to remember that it does not do any ascending or descending order on the list.
It just merely reverse the list regardless of whether the input string is already ordered or not.
The list reverse() method modifies the sequence in place for the economy of space when reversing an extensive sequence. If we want to remind employees that it operates by side effect, it does not return the reversed sequence. (Source: Python 3 Docs).
The in-place reversal has some benefits and some downsides. On the plus side, it’s a fast operation—shuffling the list elements around doesn’t require much extra memory, as we’re not creating the full copy of the list.
However, reversing the list in-place overwrites the original sort order. This could be a potential downside. (Of course, to restore the original order, you could reverse the same list again.)
From the code readability standpoint, I like this approach.
The syntax is clear and easy to understand, even for the developers new to Python or someone who comes from another language background.
List sort() and reverse() combined example
Let’s take a scenario where first we are sorting the list based on the criteria of length of string item and then reverse that order in the list.
# app.py def criteria(item): return len(item) GoT2 = ['Jon', 'Tyrion', 'Daenerys'] GoT2.sort(reverse=True, key=criteria) print (GoT2) GoT2.reverse() print (GoT2)
So, in the above example, we are descending the list based on the length of the string item and then reverse that item on the list.
So the output is the following.
If you want to learn how to sort a list in Python, then check out my list sort() method article.
Accessing Individual Elements in Reversed Order
Let us access all the items in reverse order.
# app.py GoT1 = ['Jon', 'Tyrion', 'Daenerys'] GoT1.reverse() for item in GoT1: print (item)
First, we are reverse the order of the list and then print items one by one.
Reverse a Python List Using Slicing Operator
Python’s list objects have an exciting feature called slicing.
You can view it as an extension of the square-brackets indexing syntax.
It includes the particular case where slicing a list with. “
[::-1]” produces the reversed copy.
Let’s use a Python list slice() method to reverse the list.
# app.py st = ['David', 'Millie', 'Winona'] print('Original List:', st) # Reversing a list #Syntax: reversed_list = os[start:stop:step] reversed_list = st[::-1] # updated list print('Updated List:', reversed_list)
See the output.
➜ pyt python3 app.py Original List: ['David', 'Millie', 'Winona'] Updated List: ['Winona', 'Millie', 'David'] ➜ pyt
Reversing the list this way takes up a more memory compared to an in-place reversal because it creates a (shallow) copy of the list and creating the copy requires allocating enough space to hold all of the existing items.
Note that this only creates a “shallow” copy where the container is duplicated, but not the individual list items.
Instead of duplicating the list items themselves, references to the original elements are reused in the new copy of the container.
If the items are mutable, modifying an item in the original list will also be reflected in the copy.
The biggest downside to reversing the list with a slicing syntax is that it uses a more advanced Python feature that some people would say is “arcane.”
I don’t blame them—list slicing is fast, but also a little challenging to understand the first time you encounter its quirky syntax.
When I’m reading Python code that makes use of list slicing, I often have to slow down and concentrate to “mentally parse” the statement to make sure I understand what’s going on.
My biggest gripe here is that the “
[::-1]” slicing syntax does not communicate enough that it creates a reversed copy of the original list.
Using Python’s slicing feature to reverse a list is a decent solution, but it can be challenging to read to the uninitiated.
Creating a Reverse Iterator With the reversed() Function
Reversing a list using reverse iteration with the reversed() is another option. It neither reverses a list in-place nor does it create a full copy.
Instead, we get a reverse iterator we can use to cycle through the elements of the list in reverse order.
See the following code.
# app.py st = ['David', 'Millie', 'Winona'] print('Original List:', st) for item in reversed(st): print(item)
See the output.
➜ pyt python3 app.py Original List: ['David', 'Millie', 'Winona'] Winona Millie David ➜ pyt
Finally, Python List reverse() function is over.