Python list stores zero, single or more items in a row. These list items can be reversed in different ways. In this tutorial, we will learn different Python list reversing techniques like reversed() method, reverse() method, slicing technique. Keep in mind that the list is a similar type to the array and these techniques can be called a reverse array in Python too.
Reverse Python List with reversed() Method
The reversed() method is do not directly reverse a list. The reversed() method returns the reversed iterator of the given list or sequence. This can be used in a function to reverse a list. In the following example we create a function named Reverse which reverse given list by using the reversed() method and iterator.
# Reversing a list using reversed()
def Reverse(lst):
return [item for item in reversed(lst)]
# Number list which is sorted
lst = [ 1 , 2 , 3 , 4 , 5 ]
# Reverse allready sorted number list
print(Reverse(lst))
[5, 4, 3, 2, 1]
Reverse Python List with reverse() Method
The list type or list object provides the reverse() builtin method. The reverse() method can be used to reverse the current list easily. The reverse() method reverse the current list in place so there is not need to assing into a new list.
# Number list which is sorted
lst = [ 1 , 2 , 3 , 4 , 5 ]
# Reverse list with reverse() method
lst.reverse()
# Print reversed list
print(lst)
[5, 4, 3, 2, 1]
Reverse Python List with List Slicing
The list slicing technique is very popular technique used for different things one of them is reversing list. By using list slicing technique the list is sorted no in-place and sorted list is returned which can be assigned into a new list variable.
# Number list which is sorted
lst = [ 1 , 2 , 3 , 4 , 5 ]
# Reverse list with reverse() method
reversed_list = lst[::-1]
# Print reversed list
print(reversed_list)
[5, 4, 3, 2, 1]