There are three ways to reverse a list in Python.
- List reverse() function
- Using Slicing
- Built-in reversed() function
Let’s look into all these ways to reverse a list through simple examples.
Python Reverse List using reverse() function
skills = ['Java', 'Python', 'Android'] print(skills) # using list reverse() function to reverse the list skills.reverse() print(skills)
['Java', 'Python', 'Android'] ['Android', 'Python', 'Java']
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.
numbers_asc = [1, 2, 3, 4, 5] numbers_desc = numbers_asc[::-1] print(numbers_asc) print(numbers_desc)
[1, 2, 3, 4, 5] [5, 4, 3, 2, 1]
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()
vowels = ['a', 'e', 'i', 'o', 'u'] vowels_rev = list(reversed(vowels)) print(vowels) print(vowels_rev)
['a', 'e', 'i', 'o', 'u'] ['u', 'o', 'i', 'e', 'a']
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.