How to Reverse a List in Python
Published on Aug. 22, 2023, 12:16 p.m.
To reverse a list in Python, you can use the reverse()
method or the slicing notation.
Using the reverse()
method:
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list) # Output: [5, 4, 3, 2, 1]
Using the slicing notation:
my_list = [1, 2, 3, 4, 5]
my_list = my_list[::-1]
print(my_list) # Output: [5, 4, 3, 2, 1]
Both of these methods will reverse the order of the elements in the list.
Note that the reverse()
method modifies the original list in place, whereas the slicing method creates a new reversed list.