Python List reverse() Method

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.Visual Representation of How to Use List reverse() Method

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.Visual Representation of Reversing list without modifying original list

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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.