![]() |
VOOZH | about |
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.
[6, 2, 1, 4, 3, 2, 1]
Explanation: Here, the reverse method simply reverses the list.
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.
In this example, we are reversing the list of strings using reverse() method.
['date', 'cherry', 'banana', 'apple']
In this example, we are reversing the list of mixed data types using reverse() method.
[True, 2.5, 'apple', 1]
Another common way to reverse a list in Python is using slicing ([::-1]). Let's take an example of reversing a list using slicing.
[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: