search

How to reverse a list in Python?

To reverse a list in Python, you can use either the reverse() method or the slicing syntax. Here are examples of both approaches:

Using the reverse() method:

my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)
# Output: [5, 4, 3, 2, 1]

In this example, the reverse() method is called on the list my_list, which modifies the list in-place by reversing the order of its elements.

Using the slicing syntax:

my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list)
# Output: [5, 4, 3, 2, 1]

In this example, the [::-1] slicing syntax is used to create a reversed copy of the list my_list. The [::-1] indicates that the slice should start from the end of the list and move towards the beginning with a step of -1, effectively reversing the order of the elements.

Both approaches will give you the same result: a reversed version of the original list.

Note that the first approach using the reverse() method modifies the list in-place, meaning it changes the original list itself. The second approach using slicing creates a new list object that is the reversed version of the original list. If you need to preserve the original list, use the second approach or make a copy of the list before applying the reverse() method.

Related Questions You Might Be Interested