Home » Programming » Python » Reverse A List Python

How to Reverse a List in Python

Even outside of programming, people perform list reversal regularly, for example, to re-order eBay items from high to low then low to high. It is a handy operation, and Python provides several ways to accomplish it.

Method 1: Using the built-in reverse() function

This method has the advantage of being simple and easy to understand when using someone else’s code. For example, if we have stored our list in “staffNames”:

staffNames = ["Abigail", "Chris", "Denise", "Fred"]
staffNames.reverse()

When executed, this method doesn’t automatically give a return variable, but the original list is now in reverse order, which you can verify by outputting it, for example:

print(staffNames)
["Fred", "Denise", "Chris", "Abigail"]

If you choose this method, it’s important to remember that the sequence of list items has been changed in-place, overwriting the original list order. This makes the operation fast and economical with memory, especially if it is a long list, but it isn’t always the most practical solution. For example, we might still need the list in the original sort order or be able to switch to-and-fro, which would require us to execute new sort operations repeatedly.

Method 2: List slicing

This is an application of Python’s indexing syntax. To reverse using list slicing, we use the syntax:

"[::-1]"

This is beautifully concise, but it is far from easy to spot or understand when hidden within another coder’s source code.

Indexing takes the general form “[start:end:step]” but each of the index parameters is optional, so it would be valid to specify just “[:]” in which case you will output the list items unchanged. To reverse them, you can use the syntax:

staffNames[::-1]

When you use “[::-1]” you are simply instructing python to step through the full list but in reverse order. This is a fast but more memory-hungry method than using the “reverse()” function because it creates an entirely new list with the reversed sort order. Of course, this could be a potential advantage over the first method if we have a continuing use for both list versions.

You can also use the other two indexing parameters to specify sub-ranges and perform complex operations on different list items. This could be a reason for choosing the list slicing method.

Another tip to remember is that the first item in a Python list has an index of zero, so if you intend to return a slice from the front end of a list but use the following code:

staffNames[1:3]

you will lose the first item from the list. That could result in every subsequent item being displaced by one from where you expected it to be.

Method 3: Using Python’s inbuilt “reversed()” function

Although distinguished only by one letter from the “reverse()” function, the “reversed()” function works differently. It doesn’t create a new list or container, nor does it overwrite the original; rather, it creates an “iterator” that is useful for stepping through the list in the way we need.

reversed(staffNames)

This method doesn’t create a new list of items, just a new view that references the same original list elements. Therefore, if you perform an operation on a list item in one view, it changes the corresponding element in the other.

Of course, we can still use it to create a new reversed list if we need to –

list(reversed(staffNames))

or alternatively:

for n in reversed(staffNames):
staffNames2.append(n)

Here again, the ability to step through provides an opportunity to perform additional operations on particular elements.

Method 4: Manual reversal

Using built-in functions is at least twice as fast as manually building a loop even when the list is short. They can be several hundred times faster when working on a long list. On the other hand, there are occasions when building up the operation yourself provides opportunities to insert additional operations into your routine.

The process is straightforward; for example, you can take each element from the original list in reverse order and insert them into a new list –

def reverselist(staffNames):
new = []
count = len(staffNames)-1
while count>= 0:
new.append(staffNames[count])
count -= 1
return new

This is not an exhaustive list of the possible methods for performing a list reversal. However, the key point to bear in mind is that you should always choose the most efficient method that achieves your purpose. If you need to get the length of a list, find in a list, or remove items from a list in Python, then read our other tutorial.

SHARE:
Photo of author
Author
My name is Stefan, I'm the admin of LinuxScrew. I am a full-time Linux/Unix sysadmin, a hobby Python programmer, and a part-time blogger. I post useful guides, tips, and tutorials on common Linux and Programming issues. Feel free to reach out in the comment section.

Leave a Comment