Python List reverse() is an inbuilt function that reverses the sorting order of the items. The reverse() function doesn’t return any value. It takes no parameters. It only reverses the elements and updates the list. List reverse() reverses objects of the list in place.
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.
The syntax of the reverse()
method is:
list.reverse()
reverse()
method doesn't take any arguments.reverse()
method doesn't return any value. It updates the existing list# 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]
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]
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
oss = []
oss.reverse()
print(oss)
Output
[]
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
Thanks for reading !!!
#python #python list reverse