Sometimes in a project or some kind of application we need to reverse our existing Python List. In layman language reversing can be defined as from the end to the beginning. So that what is first becomes last and what is last becomes first. In Python or other Programming Language, Python Reverse List means the same. The first element of the list becomes the last element of the Python List. And the last element of Python list becomes the first.
We have generally four ways to achieve this. But the best way to achieve the Python Reverse list is by using the reverse() function. The other three ways to reverse a list in Python are:
- (i) Using the reversed() built-in function.
- (ii) By using the slicing technique.
- (iii) By using the iterative approach or loops.
So now let’s start our tutorial to reverse a list in Python.
Reversing a List in Python using the reverse() Function
Python list class comes with the default reverse() function that inverts the order of items in the given list. It doesn’t create a new list object instead straightway modifies the original copy.
It is the most recommended way to transpose the list both from speed and performance perspective.
So we can say reverse() is an inbuilt method in Python programming language that reverses objects of the list in place.
Syntax of reverse() function:
Here list_name will be that list whose reverse you want.
Parameters in reverse()
The reverse() function in Python doesn’t take any argument.
Return Value of reverse() Function in Python
The reverse() method does not return any value in python but reverse the given object from the list.
Examples Python Reverse List Using reverse() Function
Let’s see some examples to reverse the Python List using the reverse() function.
Example 1: Basic Example to Reverse a list in Python using the reverse()
#List of Countries countries = ['USA', 'China', 'Japan', 'UK'] print('Original List of Countries:', countries) # List Reverse countries.reverse() # updated list print('Updated List of Countries:', countries)
Original List of Countries: ['USA', 'China', 'Japan', 'UK'] Updated List of Countries: ['UK', 'Japan', 'China', 'USA']
In this example, we add some elements in the list and call the reverse() method. It just reverses the elements based on their positions.
Example 2: Example to Reverse an Empty List
In this example, we are trying to check what happens when we apply reverse() function in an empty list.
# Creating a list list1 =  # Method calling list1.reverse() # Reverse elements of the list print(list1)
So we concluded it returns an empty list if the list is the list is empty.
Example 3: Using Python reverse() Function to Reverse a String
So in this example, we will check whether the reverse() functions work in a Python string or not.
# Python program to demonstrate the reverse() function in string mystring = "redlabel" mystring.reverse() print(mystring)
- Every list object in python has a method called reverse() that you can call a list object and it will reverse the list in place.
- This means we don’t need to create a new list to copy these elements to a new list but instead you can modify the original list.
- So this is very fast because it happens in a place and doesn’t take up any extra memory.
- However, it modifies the existing list.
Reversing a List in Python using the List Slicing
The second way is a trick that applies to other iterables in Python. This way is extended slice; see an example below.
The difference between the reverse method and slicing is, the list remains unchanged after reversing as using the second way. In the case of list reverse Python method, the list order is changed i.e. the original list is reversed.
def reverse_list(list): reversed_list = list[::-1] print('Old Original list :', list) print('New Reversed list:', reversed_list) number_list = [11, 22, 33, 44, 55] string_list = ['USA', 'China', 'Japan', 'UK'] reverse_list(number_list) reverse_list(string_list)
Old Original list : [11, 22, 33, 44, 55] New Reversed list: [55, 44, 33, 22, 11] Old Original list : ['USA', 'China', 'Japan', 'UK'] New Reversed list: ['UK', 'Japan', 'China', 'USA']
Slicing creates a shallow copy of the original list taking up more memory in comparison with the 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.
Advantages of Using Slicing to Reverse a List
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.
Disadvantages of Using Slicing to Reverse a List
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.
Reversing a List in Python Creating a Reverse Iterator With the Reversed() Built-in Function
The reversed() function in Python allows us to process the items in a sequence in reverse order. It accepts a sequence and returns an iterator.
Syntax of reversed() in Python:
reversed(sequence) -> reverse iterator
|Sequence to be reversed.|
Returning Value or Type of reversed() Function :
returns an iterator that accesses the given sequence in the reverse order.
Examples to Python Reverse List Using reversed Function
my_list = [1, 2, 4, 3, 5] print(list(reversed(my_list)))
[5, 3, 4, 2, 1]
Example 2: Accessing Individual Elements in Reversed Order
If you need to access individual elements of a list in reverse order, it’s better to use reversed() method in Python.
# Countries Name List countries = ['USA', 'China'] # Printing Elements in Reversed Order for c in reversed(countries): print(c)
Reversing a List in Python using the Loops
Example1: Using the Fore Loop to Reverse Python List
Instead of using inbuilt function reverse() on sequences, we will use for loop to reverse a list.
#initializing and creating the list aList = [True, 26, 'Pool', 'Python'] #copying original list is merely for size reversedList = aList.copy() len = len(aList) #reverse list using for loop for i in range(0,len): reversedList[i] = aList[len-i-1] #printing the lists print('Original List\n',aList) print('New Reversed List\n',reversedList)
Original List [True, 26, 'Pool', 'Python'] New Reversed List ['Python', 'Pool', 26, True]
Application of Reversing a List
- You change the order of a sorted list by just reversing the list. If the list is already sorted in ascending order, then by reversing the list, you get descending order.
What to Choose Between reverse() and Slicing
Extended slice syntax of Python iterator or sequence is the most preferable method to reverse a list. Although, It is the fastest method to reverse the list or any kind of iterator and most of the programmers use this method. It is not easy to understand for some beginner level programmer.
list.reverse() is clear and readable for all level of programmers but it comes in computational cost. If your
sequence is small in size then you may not notice any difference. It all depends on personal choice but it should follow the standards.
We have discussed four ways to Python reverse a list. All of them are good and easy to follow. But now the question is that which is to be used, so my answer is that “it totally depends upon situation”. You can opt for any one from them according to your problem’s needs. You can either use reverse() method, reversed() method, list slicing trick or you can also reverse the list without using any built-in function. All have their upside and downside so my suggestion is that you choose anyone which are best suited for your solution.
When we reverse items, we change their order. Note that reversing should not be confused with sorting in descending order.
If you still have any doubts or suggestions do let us know in the comment section below.