How to Reverse a List in Python | Python Program
In this article, we will learn to reverse the list using the python program.
Reverse a list using 3 methods:
- Using reverse() function
- Using reversed() function
- Using Slicing
Using reverse() function
Explanation
The reverse() function is used to reverse all the elements of the list.
Program
1 2 3 4 5 6 7 8 9 10 11 | # List List = [1, 2, 3, 4, 5, 6] # Print the original list print("Original List is ",List) # use reverse() function to reverse the list List.reverse() # print the reversed list print("Reverse List is ",List) |
Output
Original List is [1, 2, 3, 4, 5, 6] Reverse List is [6, 5, 4, 3, 2, 1]
Using reversed() function
Explanation
The Reversed() function is used while iterating, and this function reversed all the elements.
Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | # List List = [1, 2, 3, 4, 5, 6] # Print the original list print("Original List is ",List) # Make a list Reversed_List = [] # iterate the list in reverse order using reversed() function for ele in reversed(List): # append elements to the new list Reversed_List.append(ele) # print the reversed list print("Reverse List is ",Reversed_List) |
Output
Original List is [1, 2, 3, 4, 5, 6] Reverse List is [6, 5, 4, 3, 2, 1]
Using Slicing
Explanation
Using the slicing technique we easily convert our list into reverse.
Program
1 2 3 4 5 6 7 8 9 10 11 | # List List = [1, 2, 3, 4, 5, 6] # Print the original list print("Original List is ",List) # Slicing the list Reversed_List = List[::-1] # print the reversed list print("Reverse List is ",Reversed_List) |
Output
Original List is [1, 2, 3, 4, 5, 6] Reverse List is [6, 5, 4, 3, 2, 1]