Python – Reverse a List
You can reverse a Python List using list.reverse() function.
The index of each element in the list will be changed from i
to len(list)-i-1
.
reverse() performs in-place reverse. The original list gets updated to the new reversed list.
Example 1 – Reverse a Python List
In the following python program, we initialize a python list with integers and reverse the list.
example.py – Python Program
#initialize list aList = [21, 28, 14, 96, 84, 65, 74, 31] #reverse list aList.reverse() #print list print(aList)Try Online
Output
[31, 74, 65, 84, 96, 14, 28, 21]
Example 2 – Reverse List with elements of Different Datatypes
In the following example, we initialize a list with different datatypes and try to reverse the list using reverse().
example.py – Python Program
#initialize list aList = [True, 28, 'Tiger', 'Lion'] #reverse list aList.reverse() #print list print(aList)Try Online
Output
['Lion', 'Tiger', 28, True]
Example 3 – Reverse an Empty List using For Loop
Instead of using inbuilt function reverse() on sequences, we will use for loop to reverse a list.
example.py – Python Program
#initialize list aList = [True, 28, 'Tiger', 'Lion'] #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] #print lists print('Original List\n',aList) print('Reversed List\n',reversedList)Try Online
Output
Original List [True, 28, 'Tiger', 'Lion'] Reversed List ['Lion', 'Tiger', 28, True]
Example 4 – Reverse an Empty List
Of course, the reversing an empty list results in empty list.
example.py – Python Program
#initialize list aList = [] #reverse list aList.reverse() #print list print(aList)Try Online
Output
[]
Conclusion
In this Python Tutorial, we learned how to reverse a list using reverse() function with the help of example Python programs.