Python

reverse() in list

Click for All Topics

reverse() in list - Python

  • This method is used to reverse the elements of a list.
  • It modifies the original list and doesn’t return anything.
  • This method doesn’t take any argument.
  • The time complexity of this method is O(n) where n is the number of elements.
  • When we call this method with the list it first picks the first and last element of the list and swaps the position of both and the same happens with other elements of the list.

Syntax –

list.reverse()

 

Parameters –

  • argument → Doesn’t take any argument
  • return →None(Doesn’t return anything)

 

 

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]
				
			
  • In the above example, first we create a list with some elements and store it in the my_list variable
  • After creating the original list print the original list on the output screen.
  • Then call the .reverse() method with my_list and reverse the list.
  • Finally, print the reverse list on the output screen.

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]