Python list reverse()
In this article, we will take a look at reverse()
method in python list in detail and how to use it to reverse the list with examples.
Reverse here means that the first element becomes last, second element becomes second last and so on.
reverse()
is an inbuilt python list function which reverses a list in place.In place means it modifies the position of elements in the original list. This means that the original list is changed.
This method is beneficial in terms of memory usage.
Python docs for reverse()
state,
The reverse() method modifies the sequence in place for economy of space when reversing a large sequence
Python list reverse() syntax
reverse()
method is invoked on a list. It does not take any arguments and does not return any value.
If you look at the return value of reverse()
method, it returns None
since it modifies the list on which it is called.
Syntax of reverse()
is
list_obj.reverse()
Below is an example program of
reverse()
method to reverse a list of numbers.
numbers = [1,2,3,4,5] print('Original list', numbers) numbers.reverse() print('Reversed list', numbers)
Output is
Reversed list [5, 4, 3, 2, 1]
There are other methods to reverse a python list as well but this is the most easiest method.