How to Reverse the list in Python?

Python supports built-in method reverse(), reversed() which is the simplest way to reverse the items in the list. There are various other ways to reverse the list by using for loop, extended slicing, etc.

Reversing a list using the reverse() method

A list is mutable hence there is no need to create another list. This reverse() method directly modifies the original list. The reverse() method doesn't take any arguments and doesn't return any value. The syntax for the reverse() method is as follows.

syntax:
list.reverse()

For example, let us consider a list my_list = [1, 2, 3, 4, 5]. The reverse() method reverse the items of the list and update the my_list to [5, 4, 3, 2, 1].

my_list = list(map(int,input("Enter the items in list:").split()))
my_list.reverse()
print("The reversed list is :",my_list)

Output

Enter the items in list: 1 2 3 4 5
The reversed list is : [5, 4, 3, 2, 1]

Reversing a list using the reversed() method

The reversed() method is a built-in method that is used to reverse a list. It takes a single argument which can be any sequence like lists, tuples, etc. It doesn't modify the original list. The reversed() method returns an iterator in reverse order. The syntax for the reversed() method is as follows.

syntax:
   reversed(iterable)

For example, let us consider a list my_list = [1, 2, 3, 4, 5]. The reversed() method reverses the items of the list and returns the reversed iterator to rev_list.

my_list = list(map(int,input("Enter the items in list:").split()))
print("my_list =",my_list)
rev_list = list(reversed(my_list))
print("The reversed list is :",rev_list)

Output

Enter the items in list:1 2 3 4 5
my_list = [1, 2, 3, 4, 5]
The reversed list is : [5, 4, 3, 2, 1]

Reverse a list using the extended slice

The syntax for an extended slice is [start: stop: step]. The value for the start and stop field is optional and if the value is not provided it sets the default value for start to '0' and stop to string length. Step -1 indicates starting from the end and stop at the start hence, reversing the list.

my_list = list(map(int,input("Enter the items in list").split()))
rev_list = my_list[::-1]
print("The reversed list is :",rev_list)

Output

Enter the items in list 1 2 3 4 5
The reversed list is : [5, 4, 3, 2, 1]

Reverse a list using for loop

A for loop can be used to reverse a list. In the below code the range of for loop is set to (len(my_list)-1, -1, -1). The for loop here is used to iterate over the list in a reverse way and each item is appended to a new_list.

new_list=[]
my_list = [1, 2, 3 , 4, 5]
print("my_list = ",my_list)
for item in range(len(my_list)-1 ,-1 ,-1):
    new_list.append(my_list[item])
print("new_list = ",new_list)

Output

my_list =  [1, 2, 3, 4, 5]
new_list =  [5, 4, 3, 2, 1]
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions