Reversing a list is a common requirement in any programming language. In this tutorial, we will learn the effective way to reverse a list in Python.
There are 3 ways to reverse a list in Python.
reversed()
built-in functionreversed()
is a built-in function in Python. In this method, we neither modify the original list nor create a new copy of the list. Instead, we will get a reverse iterator which we can use to cycle through all the elements in the list and get them in reverse order, as shown below.
# Reversing a list using reversed()
def reverse_list(mylist):
return [ele for ele in reversed(mylist)]
mycountrylist = ['US','India','Germany','South Africa']
mynumberlist = [1,2,3,4,5,6]
print(reverse_list(mycountrylist))
print(reverse_list(mynumberlist))
Output
['South Africa', 'Germany', 'India', 'US']
[6, 5, 4, 3, 2, 1]
If we need a copy of the reversed list, we could use the below code to perform this operation.
mynumberlist = [1,2,3,4,5,6]
newlist = list((reversed(mynumberlist)))
print(newlist)
# Output
# [6, 5, 4, 3, 2, 1]
reverse()
is a built-in function in Python. In this method, we will not create a copy of the list. Instead, we will modify the original list object in-place. It means we will copy the reversed elements into the same list.
The reverse()
method will not return anything as the list is reversed in-place. However, we can copy the list before reversing if required.
# Reversing a list using reverse()
def reverse_list(mylist):
mylist.reverse()
return mylist
mycountrylist = ['US','India','Germany','South Africa']
mynumberlist = [1,2,3,4,5,6]
print(reverse_list(mycountrylist))
print(reverse_list(mynumberlist))
Output
['South Africa', 'Germany', 'India', 'US']
[6, 5, 4, 3, 2, 1]
Slice notation allows us to slice various collection objects such as lists, strings, tuples, and Numpy Arrays.
The slicing trick is the simplest way to reverse a list in Python. The only drawback of using this technique is that it will create a new copy of the list, taking up additional memory.
# Reversing a list using slicing technique
def reverse_list(mylist):
newlist= mylist[::-1]
return newlist
mycountrylist = ['US','India','Germany','South Africa']
mynumberlist = [1,2,3,4,5,6]
print(reverse_list(mycountrylist))
print(reverse_list(mynumberlist))
Output
['South Africa', 'Germany', 'India', 'US']
[6, 5, 4, 3, 2, 1]
Also published on https://itsmycode.com/python-reverse-a-list-a-step-by-step-tutorial/.