Last Updated On By Khizer Ali
Table of Contents
The reverse() method can reverse the items of the list object in-place. Using this method, we don’t need to create a new list because it copies the items inside the list, reverses all the items, and modifies the original list.
list.reverse()
It does not take any argument. Let’s have a look at an example.
o_list = [16, 3, 75, 37]
print("original list : ", o_list)
o_list.reverse()
print("reversed list : ", o_list)
We can see that the reverse() method reversed all the items in the list. If we print the list object directly on the reverse() method, it will return the special value None because it is modifying the original list, not creating a new list. Let’s examine it through an example.
o_list = [16, 3, 75, 37]
print("Directly calling list object : ", o_list.reverse())
Here we can see we are getting None when we are calling the list object directly.
This technique will create a copy of the list but not sorted in-place. That means it will occupy more space in memory.
list[::-1]
Let’s have a look at an example.
o_list = [16, 3, 75, 37]
print("original list : ", o_list)
r_list = o_list[::-1]
print("reversed list : ", r_list)
In this technique, we can call the object directly and get the reversed list. This technique will not return the special value None because it creates a copy of the original list. Let’s see this through an example.
o_list = [16, 3, 75, 37]
print("directly calling : ", o_list[::-1])
Here we are getting the reversed list as a copy of the original list.
This method will neither create a new copied list nor modify the original list. Instead, it will simply iterate the list items in reverse order.
for items in reversed(list):
Let’s have a look at an example.
o_list = [16, 3, 75, 37]
print("original list : ", o_list)
for item in reversed(o_list):
print("iterated item : ", item)
As shown in the example above, the reversed() method gives us the reversed list by iterating through its items.