Python List reverse() method is used to reverse the elements of the list. This method doesn’t return a new list but modifies the original list.
Syntax
list.reverse()
Parameters
This method doesn’t take any arguments.
Return value
It does not return anything. Instead, it modifies the list in place.
Example 1: How to Use List reverse() Method
# Create a list
my_list = [1, 2, 3, 4, 5]
# Print the original list
print(f"Original list: {my_list}")
# Reverse the list using the reverse() method
my_list.reverse()
# Print the reversed list
print(f"Reversed list: {my_list}")
Output
Original list: [1, 2, 3, 4, 5]
Reversed list: [5, 4, 3, 2, 1]
Example 2: Reversing a list without modifying the original
To create a new reversed list without modifying the original one, you can use the [::-1] slicing technique.
original_list = [1, 2, 3, 4, 5]
reversed_list = original_list[::-1]
print(reversed_list)
Output
[5, 4, 3, 2, 1]
Example 3: Accessing elements in reversed order
If you need to access individual list elements in reverse order, you can use the “reversed()” function.
# Operating System List
oss = ['Windows', 'macOS', 'Linux']
# Printing Elements in Reversed Order
for o in reversed(oss):
print(o)
Output
Linux
macOS
Windows
Example 4: Sorting an empty list
oss = []
oss.reverse()
print(oss)
Output
[]
Example 5: Comparing output after reversing
car = ['b', 'm', 'w', 'p', 'a']
car2 = ['a', 'p', 'w', 'm', 'b']
car.reverse()
if car == car2:
print("Both are equal")
else:
print("Not equal")
Output
Both are equal
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.