Python Reverse List With Examples

There are three ways to reverse a list in Python.

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

python reserve list

 

Python Reverse List

Let’s look into all these ways to reverse a list through simple examples.

Python Reverse List using reverse() function

Output:

 

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.

Output:

 

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.

Output:

 

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()

By admin

Leave a Reply

%d bloggers like this: