Computer >> Computer tutorials >  >> Programming >> Python

How to reverse the objects in a list in Python?


You can use the reverse method from the list class to reverse a list in place.  

example

a = [3, "Hello", 2, 1]
a.reverse()
print(a)

Output

This will give the output −

[1, 2, "Hello", 3]

You can also use list slicing with the index as [::-1] If you want a new list to be made instead of reversing in place. This means take the start and stop as start and end of list and step as -1. 

example

a = [3, "Hello", 2, 1]
print(a[::-1])

Output

This will give the output −

[1, 2, "Hello", 3]

If you want a new list to be made instead of reversing in place, you can also use the reversed method.

example

a = [3, "Hello", 2, 1]
rev_a = list(reversed(a))
print(rev_a)

Output

This will give the output −

[1, 2, "Hello", 3]