How to use reverse() in Python
The built-in Python reverse() function is used to reverse the order of objects in a list data structure in place.
Syntax
list.reverse()
Parameters
This function takes no parameters.
Return value
-
This function does not
returnanything. -
The
listthat calls the function is updated in place. -
If the function is called by an object that is not a list, an
Attribute Erroris returned.
Code
# creating a listlistTest1 = [5, 4, 3, 2, 1]# printing the listprint("list before reversing: ")print(listTest1)# call reverse on first listlistTest1.reverse()print("\nlist after reversing: ")print(listTest1) # list is updated# creating another listlistTest2 = ["one", "two", "three", "four", "five"]# printing second listprint("\nlist before reversing: ")print(listTest2)# call reverse on second listlistTest2.reverse()print("\nlist after reversing: ")print(listTest2) # list is updated# this will throw Attribute ErrornotAList = 536# calling reverse with an onject that is not a listnotAList.reverse()
reverse() vs. reversed()
The reversed() function takes any sequence as an argument and returns a reversed iterator object. The iterator object accesses the objects of the sequence in reverse order.
On the other hand, reverse() does not take any arguments, nor does it return anything. The changes are made to the original list itself.