Mastering Python (97 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (32 Blogs)
  • Data Science (26 Blogs)
  • Mastering Python (92 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

How to Reverse a List in Python: Learn Python List Reverse() Method

Last updated on Jul 15,2021 12K Views

Aayushi Johari
A technophile who likes writing about different technologies and spreading knowledge. A technophile who likes writing about different technologies and spreading knowledge.
38 / 62 Blog from Python Fundamentals

Rise of Python programming has seen a surge in the number of people wanting to study Python for a better career opportunity. While going through Python Fundamentals, you would realize that occasionally reversing a string in Python makes accessing data easier. In this article, we will take a look at a step-by-step tutorial to reverse a list in Python using various ways.

This article will focus on the following pointers:

Let us get started.

Reversing a list with list.reverse() method

Every list in Python has a built-in reverse() method, you can call this method to reverse the contents of the list object in-place. Reversing a list in-place means it won’t create and copy the existing elements to a new list. Instead, it directly modifies the original list object.

Before we proceed make sure you Python installed on your system.

Here’s an example:

Example 1:

number_list = [10, 20, 30, 40, 50]
reversed_list = number_list.reverse()
print(reversed_list)
number_list = [10, 20, 30, 40, 50]
reversed_list = number_list.reverse()
print(reversed_list)

Output:

None

Example 2:

string_list = [“One”, “Two”, “Three”, “Four”, “Five”]
reversed_list = string_list.reverse()
print(reversed_list)

Output:

None

Example 3:

def reverse_list(list):
    print(‘Old list:’, list)
    list.reverse()
    print(‘New list:’, list)
 
number_list = [10, 20, 30, 40, 50]
string_list = [“One”, “Two”, “Three”, “Four”, “Five”]
reverse_list(number_list)
reverse_list(string_list)

Output:

Old list: [10, 20, 30, 40, 50]
New list: [50, 40, 30, 20, 10]
Old list: [‘One’, ‘Two’, ‘Three’, ‘Four’, ‘Five’]
New list: [‘Five’, ‘Four’, ‘Three’, ‘Two’, ‘One’]

Explanation

As you can see, calling reverse() returned ‘None’ but, modified the original list object. This is how the Python standard library was developed by the developers.

The reverse() method modifies the sequence in place for the economy of space when reversing a large sequence. The side effect of this is that it does not return a reversed list but it returns ‘None.’

An in-place reversal has some benefits and some disadvantages. The benefit of this is that it operates very fast as it shuffles the list elements and does not create new list, hence saving memory, required to store a reversed list. As it overrides the original list, this could be a disadvantage. However, we can reverse the list again to bring it back to the original state.

The syntax is simple and easy. This means beginners or developers from another language or background would find the code readable.

Using the Slicing Trick to Reverse a Python List

Python has a fascinating feature for a list called slicing. Where you can produce a reversed copy of list using slicing feature with “[::-1]”.

Here’s an example:

def reverse_list(list):
    reversed_list = list[::-1]
    print(‘Old list:’, list)
    print(‘New list:’, reversed_list)
 
number_list = [10, 20, 30, 40, 50]
string_list = [“One”, “Two”, “Three”, “Four”, “Five”]
reverse_list(number_list)
reverse_list(string_list)

Output:

Old list: [10, 20, 30, 40, 50]
New list: [50, 40, 30, 20, 10]
Old list: [‘One’, ‘Two’, ‘Three’, ‘Four’, ‘Five’]
New list: [‘Five’, ‘Four’, ‘Three’, ‘Two’, ‘One’

Explanation

It creates a shallow copy of the original list taking up more memory in comparison with in-place reversal. As it creates a copy it requires more space to hold all the existing elements.

The point to note here is that structure of the list is replicated and not the contained objects i.e elements in a list. Hence, the elements are not duplicated thus saving space. Also only the references in the structure holding addresses of objects are updated. As mutability applies to the elements contained in a list. If the object is modified it will be reflected in other copies as well.

Slicing is fast. But it is difficult to understand decreasing readability of code as you go through the code. Since it is fast its developer’s responsibility to use appropriate options depending on the scenario.

Understanding the script which is written using slicing could be time-consuming and difficult to visualize. The syntax is complex and doesn’t give a clear picture of what it is doing.

Creating Reverse Iterator with the reversed() Built-In Function

The reversed() function will return an iterator with which we can access elements in reverse order. If the requirement is such that you need to access an individual element of the list in reverse order you can use this function. It does not reverse a list in-place neither it creates a copy.

Here’s an example:

def reverse_list(list):
    reversed_list = []
        for o in reversed(list):
            reversed_list.append(o)
    print(‘Old list:’, list)
    print(‘New list:’, reversed_list)
 
number_list = [10, 20, 30, 40, 50]
string_list = [“One”, “Two”, “Three”, “Four”, “Five”]
reverse_list(number_list)
reverse_list(string_list)
Output:
Old list: [10, 20, 30, 40, 50]
New list: [50, 40, 30, 20, 10]
Old list: [‘One’, ‘Two’, ‘Three’, ‘Four’, ‘Five’]
New list: [‘Five’, ‘Four’, ‘Three’, ‘Two’, ‘One’]

Output:

Old list: [10, 20, 30, 40, 50]
New list: [50, 40, 30, 20, 10]
Old list: [‘One’, ‘Two’, ‘Three’, ‘Four’, ‘Five’]
New list: [‘Five’, ‘Four’, ‘Three’, ‘Two’, ‘One’]

Explanation

All this function does is, it returns element of the list in reverse order using iterator pattern so the elements of the list can be traversed in reverse order.

Another way of getting a reverse list using list constructor and reversed function resulting in compact code is demonstrated below.

mylist = [1, 2, 3, 4, 5]
list(reversed(mylist))

Output

[5, 4, 3, 2, 1]

Explanation

The list constructor iterates over the list in reverse order. This happens until the last element is reached. It also creates a shallow copy of the original list in the reverse order giving the desired output.

This piece of code is readable and can be easily visualized. It gives a clear picture of what is going on in the background. An iterator is an important concept, understanding it at a deeper level would be helpful but not necessary to use every time.

This brings us to the end of this article. In this article, we covered the different ways to reverse a list in python. We have seen their pros and cons. In case if you wish toget in-depth knowledge on Python along with its various applications, you can enroll now for live Python online training with 24/7 support and lifetime access.

Got a question for us? Mention them in the comments section of “reverse a list in Python” and we will get back to you.

Upcoming Batches For Data Science with Python Certification Course
Course NameDate
Data Science with Python Certification Course

Class Starts on 13th February,2023

13th February

MON-FRI (Weekday Batch)
View Details
Data Science with Python Certification Course

Class Starts on 25th February,2023

25th February

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How to Reverse a List in Python: Learn Python List Reverse() Method

edureka.co