There are three ways to reverse a list in Python.
- List reverse() function
- Using Slicing
- Built-in reversed() function
Python Reverse List
Let’s look into all these ways to reverse a list through simple examples.
Python Reverse List using reverse() function
1 2 3 4 5 6 7 |
skills = ['Java', 'Python', 'Android'] print(skills) # using list reverse() function to reverse the list skills.reverse() print(skills) |
Output:
1 2 3 4 5 |
['Java', 'Python', 'Android'] ['Android', 'Python', 'Java'] <img class="alignnone wp-image-22496 size-full" src="http://all-learning.com/wp-content/uploads/2019/01/Python-Reverse-List.png" alt="Python Reverse List " width="1200" height="628" /> |
Python List reverse() function
This is a very fast function which reverses the list elements in place. So the original list is modified and if it was sorted then that is gone too. Sometimes we don’t want that and want a new list in the reversed order.
Reverse and Create new list using Slicing
We can use slicing to create a new list in the reverse order. Let’s look at an example.
1 2 3 4 5 6 |
numbers_asc = [1, 2, 3, 4, 5] numbers_desc = numbers_asc[::-1] print(numbers_asc) print(numbers_desc) |
Output:
1 2 3 4 5 |
[1, 2, 3, 4, 5] [5, 4, 3, 2, 1] <img class="alignnone wp-image-22497 size-full" src="http://all-learning.com/wp-content/uploads/2019/01/Python-Reverse-List-Using-Slicing.png" alt="Python Reverse List Using Slicing" width="1200" height="628" /> |
Python Reverse List Using Slicing
Here the original list is not modified. It’s a simple one-liner method to reverse a list. However, the syntax is not easy to understand if you are not aware of slicing techniques in python.
Python Reverse a List using reversed()
We can use reversed() built-in function to create a reverse iterator and then use it with list() function to create a new list with elements in reverse order.
1 2 3 4 5 6 |
vowels = ['a', 'e', 'i', 'o', 'u'] vowels_rev = list(reversed(vowels)) print(vowels) print(vowels_rev) |
Output:
1 2 3 4 5 |
['a', 'e', 'i', 'o', 'u'] ['u', 'o', 'i', 'e', 'a'] <img class="alignnone wp-image-22498 size-full" src="http://all-learning.com/wp-content/uploads/2019/01/Python-Reverse-List-using-reversed-Iterator.png" alt="Python Reverse List using reversed() Iterator" width="1200" height="628" /> |
Python Reverse List using reversed() Iterator
Conclusion
If you want to reverse a list in place, then use the reverse() function. However, if you want to keep the original list intact, then you can use slicing as well as reversed() iterator. However, slicing technique is hard to understand and reversed() is easy to read and understand.
References: Python List Functions, reversed()