Python List reverse() Method: How To Reverse List In Python

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.

Syntax of List reverse()

The syntax of the reverse() method is:

list.reverse()

reverse() parameter

  • The reverse() method doesn't take any arguments.

Return Value from reverse()

  • The reverse() method doesn't return any value. It updates the existing list

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

Thanks for reading !!!

#python #python list reverse

Python List reverse() Method: How To Reverse List In Python
14.25 GEEK