Click for All Topics
Syntax –
list.reverse()
Parameters –
Example 1-
my_list=[1,10,100,1000,10000,100000]
print("Orignal list:",my_list)
my_list.reverse()
print("Reversed list:",my_list)
# Output -
# Orignal list: [1, 10, 100, 1000, 10000, 100000]
# Reversed list: [100000, 10000, 1000, 100, 10, 1]
.reverse()
method with my_list and reverse the list.Example 2- let’s see the return value of the .reverse()
method
lst=['a','b','c','d','e']
print("Original list:",lst)
return_value=lst.reverse()
print("Reverse list:",lst)
print("Return value of reverse:",return_value)
# Output -
# Original list: ['a', 'b', 'c', 'd', 'e']
# Reverse list: ['e', 'd', 'c', 'b', 'a']
# Return value of reverse: None
Example 3- reverse a list without using an in-built function or method / reverse a list using slicing
subject=['Hindi','English','Math','Physics', 'Chemistry']
print("Original list:",subject)
subject=subject[::-1]
print("Reversed subject list:",subject)
# Output -
# Original list: ['Hindi', 'English', 'Math', 'Physics', 'Chemistry']
# Reversed subject list: ['Chemistry', 'Physics', 'Math', 'English', 'Hindi']
Example 4- reverse a list without using an inbuilt method or function and without using slicing operator
my_list = [1, 2, 3, 4, 5]
print("Original list:",my_list)
left = 0
right = len(my_list) - 1
while left < right:
# Swap the elements at left and right indices
my_list[left], my_list[right] = my_list[right], my_list[left]
# Move the left index to the right, and the right index to the left
left += 1
right -= 1
print("Reversed list:",my_list)
# Output -
# Original list: [1, 2, 3, 4, 5]
# Reversed list: [5, 4, 3, 2, 1]
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India