How to reverse lists in Python
Reverse lists in Python
Lists are built-in data types in Python. In other words, they are collections of data. And we use them for data storage.
Often, when we store data in Python (especially with lists), we need to reverse it. This is possible through several methods.
In this tutorial, we cover:
- Reversed() built-in function
- Reverse slicing (negative)
- Reverse() lists method
For more information regarding lists, press here.
All three methods have different characteristics. Let’s explore them one by one.
Reversed()
This approach uses the built-in Python function reversed(). Reversed() does not modify the original list.
The function can be implemented directly through a print statement or stored in a variable first. It can also be executed through a for loop.
With a print statement
numbers = [1, 2, 3, 4, 5] print(list(reversed(numbers))) print(numbers) # Output: [5, 4, 3, 2, 1] # Output: [1, 2, 3, 4, 5]
Stored in a variable
numbers = [1, 2, 3, 4, 5] new = list(reversed(numbers)) print(new) print(numbers) # Output: [5, 4, 3, 2, 1] # Output: [1, 2, 3, 4, 5]
With a for loop
numbers = [1, 2, 3, 4, 5] for n in reversed(numbers): print(n)
5 4 3 2 1
Reverse slicing
This method uses slicing, specifically negative slicing. Reverse slicing does not change the original list.
You can execute negative slicing with a print statement or store it inside a variable beforehand.
Print statement
numbers = [1, 2, 3, 4, 5] print(numbers[::-1]) print(numbers) # Output: [5, 4, 3, 2, 1] # Output: [1, 2, 3, 4, 5]
Inside a variable
numbers = [1, 2, 3, 4, 5] new = numbers[::-1] print(new) print(numbers) # Output: [5, 4, 3, 2, 1] # Output: [1, 2, 3, 4, 5]
Reverse()
This approach uses the reverse() lists function. Reverse() modifies the original list.
The method applies directly onto the list.
numbers = [1, 2, 3, 4, 5] numbers.reverse() print(numbers) # Output: [5, 4, 3, 2, 1]
We can see that once the function applies to the list, the original list (numbers) changes.