Data Science and Machine Learning Internship ...
- 1k Enrolled Learners
- Weekend/Weekday
- Live Class
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:
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.
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.
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.
Course Name | Date | |
---|---|---|
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 |
edureka.co