Sometimes we need to reverse the list in Python. In this tutorial, we will learn how to reverse a list in Python.
1. Using the list reverse method
The list.reverse() method will reverse the elements of the list in place.
Syntax of the list reverse method :
list.reverse()
Arguments: Reverse method does not take any parameters.
Returns: Does not return any value, however it updates the list in place.
Let’s see the pros and cons of this method.
Pros:
- It is a fast operation, it does not require extra memory. We are not creating copy of the list.
- It is more readable.
Cons:
- Since it is an in-place operation it overwrites the original sort order.
Example
A simple example of list.reverse().
#Create a list of even numbers
even_numbers = [2,4,6,8,10]
# Reverse the list
even_numbers.reverse()
print(f"Reversed list {even_numbers}")
Output
Reversed list: [10, 8, 6, 4, 2]
2. Reverse list using the list slicing trick
Another way to reverse the list using the [: :-1] list slicing trick. List slicing syntax is [start : stop : step], to reverse the list we will use step size as -1; we can write it as list[ : :-1].
Example
# Create a list of devices
devices = ["printer","keyboard","mouse"]
#Reverse using list slicing
reversed_devices = devices[::-1]
print(f"Reversed list: {reversed_devices}")
Output
Reversed list: ['mouse', 'keyboard', 'printer']
Let’s see the pros and cons of this method.
Pros:
- It does not modify the original list.
Cons:
- It takes more memory and creates a shallow copy of the list.
- List slicing is an advanced feature so beginners may feel a bit difficult to use.
3. Reverse list using the reversed function
To reverse a list we can use the inbuilt reversed function. The syntax of the reversed function is
reversed(seq)
Parameters: Sequence ( strings, lists, tuples).
Returns: Reversed iterator.
Example
#Create a list of numbers
numbers = [1,2,3,4,5]
# Reverse the list
reversed_numbers = list(reversed(numbers))
print(f"Reversed list: {reversed_numbers}")
Output
Reversed list: [5, 4, 3, 2, 1]
Here revered list iterator is converted to a list using “list(reversed(numbers))”.
We can iterate the reversed list as shown below:
#Create a list of numbers
numbers = [1,2,3,4,5]
for number in reversed(numbers):
print(number)
Output
5
4
3
2
1
This method has some advantages:
- It doesn’t modify the original list.
- It only returns the reversed iterator, sometimes we might need to convert it to a list.
Conclusion
That’s all about the three different ways to reverse a list in Python.