Summary: In this tutorial, we will learn to reverse a list in Python using the list.reverse() method.

The list.reverse() is the built-in list method in Python that reverses the items of the list in-place i.e. it doesn’t require an auxiliary list but modifies the original list.

For example, in the following code, the reverse method reverses the list in-place:

>>> l = [1, 2, 3, 4, 5]
>>> l.reverse()
>>> print(l)
[5, 4, 3, 2, 1]

Parameter and Return Value

The list.reverse() method does not accept any parameters nor does it return any value.

It just reverses the list in-place.

Examples using list.reverse()

Example 1: Reverse a list of strings using the list.reverse() method

>>> l = ['Ak', 'Rock', 'Emily']
>>> l.reverse()
>>> print(l)
['Emily', 'Rock', 'Ak']

Example 2: Iterate through the list in reverse order

>>> l = [1, 2, 3, 4, 5]
>>> for x in l.reverse():
...     print(x*x)
... 
TypeError: 'NoneType' object is not iterable

Because l.reverse() returns nothing (which is represented by the class NoneType in Python), we cannot iterate over it using the ‘for’ loop.

We can verify this using the type() method:

>>> type(l.reverse())
<class 'NoneType'>

The type() method in Python returns the class type of the object passed as the parameter.

If we intend to iterate through the list in reverse order then we should use the slicing operator as follows:

>>> l = [1, 2, 3, 4, 5]
>>> for x in l[::-1]:
...     print(x*x, end=' ')

25 16 9 4 1 

Conclusion

The list.reverse() method in Python in-place reverses the list object. It doesn’t accept any parameter and doesn’t return any value.

Leave a Reply