The reverse()
method is used to reverse the order of elements in a list. It is a built-in method available for lists in Python.
reverse()
method:
list_name.reverse()
list_name
: This is the name of the list that you want to reverse.The reverse()
method modifies the original list in place, meaning it does not create a new list with the reversed elements. Instead, it directly changes the order of elements within the existing list.
# Create a list
my_list = [1, 2, 3, 4, 5]
# Reverse the list
my_list.reverse()
print(my_list) # Output: [5, 4, 3, 2, 1]
As you can see, the reverse()
method reversed the order of elements in the original list. The first element became the last, the second element became the second-to-last, and so on. Keep in mind that the reverse()
method modifies the original list and does not create a new list with the reversed elements. If you want to preserve the original list and create a reversed copy, you can use slicing with a step of -1:
# Create a list
my_list = [1, 2, 3, 4, 5]
# Create a reversed copy of the list using slicing
reversed_copy = my_list[::-1]
print(reversed_copy) # Output: [5, 4, 3, 2, 1]
print(my_list) # Output: [1, 2, 3, 4, 5] (Original list remains unchanged)
In this example, the [::-1]
slicing syntax creates a new list with the elements of the original list in reverse order, while the original list remains unchanged.