Python Reverse List

Filed Under: Python

There are three ways to reverse a list in Python.

  1. List reverse() function
  2. Using Slicing
  3. Built-in reversed() function
Python Reverse List

Python Reverse List

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)

Output:


['Java', 'Python', 'Android']
['Android', 'Python', 'Java']
Python List reverse() function

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.


numbers_asc = [1, 2, 3, 4, 5]
numbers_desc = numbers_asc[::-1]
print(numbers_asc)
print(numbers_desc)

Output:


[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
Python Reverse List Using Slicing

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.


vowels = ['a', 'e', 'i', 'o', 'u']
vowels_rev = list(reversed(vowels))
print(vowels)
print(vowels_rev)

Output:


['a', 'e', 'i', 'o', 'u']
['u', 'o', 'i', 'e', 'a']
Python Reverse List using reversed() Iterator

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.

You can checkout complete python script and more Python examples from our GitHub Repository.

References: Python List Functions, reversed()

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages