Method #1: In-Place Reverse List
According to Python Document, we can use the built-in
reverse() method to reverse a list in place. It’s easy, however, we should notice the “in-place”. It means this method will modify your original list directly.
>>>A = [1, 2, 3, 4, 5] >>>print(A.reverse()) None >>>A [5, 4, 3, 2, 1]
As you can see in the example,
A.reverse() will return
None. However, list A has reversed itself. Understanding how the method work is very important. From my experiences, there are many bugs that come from this misunderstanding.
By reversing the original list, the in-place method brings you a memory benefit. Instead of copy the whole list, reverse and return it, it is reversed directly. You can save your memory, especially with the big list.
In the other hand, you can get the wrong data when trying to
return A.reverse(). Instead of receiving the reversed data, you will receive a
Method #2: Slicing List With [::-1] Expression
This is a very special expression in Python. By using expression between brackets, you can reverse a list easily. This method called the slicing feature, there are many other useful expressions in the official document.
Here is an example:
>>>A = [1, 2, 3, 4, 5] >>>A[::-1] [5, 4, 3, 2, 1]
With the slicing method, we are able to receive the reversed list without modifying the original version. It is meaningful in case we need to keep the original order of the list for another logic.
However, slicing is looked complicated and hard to understand, especially with a newbie. Of course, I don’t blame it, I love it more. I mean any method has its own pros and cons. Slicing is super fast, but if you are new with Python, it’s hard to understand its meaning.
When I first saw this expression to reverse a list. I have no idea what is it and even don’t know the keyword to research it more.
Method #3: Using a Reverse Iterator
In Python, an iterator is an object that you can traverse through all the values. So reverse iterator means we will iterate an object in reverse direction.
Let’s how we do it:
>>> A = [1, 2, 3, 4, 5] >>> for el in reversed(A): ... print(el) ... 5 4 3 2 1 >>> A [1, 2, 3, 4, 5]
By calling a handy built-in method
reversed(), I can loop over the list in reverse order.
reversed() method didn’t change the original list. However, we’re able to keep the reverse version if you want. Do as below:
>>> list(reversed(A)) [5, 4, 3, 2, 1]
So far, we get to know 3 different methods to reverse a list in Python. These methods are in-place reverse, slicing list and reverse iterator.
Each method has its own pros and cons. Choosing which method totally belongs to you.
You may also want to look at other powerful techniques in Python as below. It’s absolutely sure that these techniques will make our code shorter, cleaner and even more professional.