Python List Reverse()
The reverse() method is an inbuilt method in Python that reverses the order of elements in a list. This method modifies the original list and does not return a new list, which makes it an efficient way to perform the reversal without unnecessary memory uses.
Let's see an example to reverse a list using the reverse() method.
a = [1, 2, 3, 4, 1, 2, 6]
a.reverse()
print(a)
Output
[6, 2, 1, 4, 3, 2, 1]
Explanation: Here, the reverse method simply reverses the list.
Syntax of List reverse()
list_name.reverse()
Parameters: It doesn't take any parameters.
Return Value: It doesn't return any value.
Note: The reverse() method is specific to lists in Python (it's an attribute of a list). Therefore, attempting to use the reverse() method on other data structures, such as strings, tuples, sets, or dictionaries, will result in an error.
Example of List reverse()
Reversing a list of strings
In this example, we are reversing the list of strings using reverse() method.
a = ["apple", "banana", "cherry", "date"]
a.reverse()
print(a)
Output
['date', 'cherry', 'banana', 'apple']
Reverse a list of mixed data types
In this example, we are reversing the list of mixed data types using reverse() method.
a = [1, 'apple', 2.5, True]
a.reverse()
print(a)
Output
[True, 2.5, 'apple', 1]
Reverse() vs. Slicing Approach
Another common way to reverse a list in Python is using slicing ([::-1]). Let's take an example of reversing a list using slicing.
a = [1, 2, 3, 4, 5]
res = a[::-1]
print(res)
Output
[5, 4, 3, 2, 1]
Explanation: The slicing approach [:: -1] creates a new list, which requires additional memory, whereas reverse() modifies the existing list.
Note: If we want to keep the original list without modifying it then should use slicing. But if we need to change the list directly then use reverse().
Related Article: