Why list reverse returns Null?

Question:

I have example list like this:

l = [1,2,3]

print(l.reverse())
#give None instead [3, 2, 1]

How is that? How can I reverse list?

Asked By: user3654650

||

Answers:

How can I reverse list?

The list is being reversed. But list.reverse reverses in place, and does not return anything to the caller. You can verify this by printing the list after calling reverse on it:

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

If in doubt, use the help:

>>> help(list.reverse)

Help on method_descriptor:
reverse(...)
    L.reverse() -- reverse *IN PLACE*

(Python 2.7 documentation)

Answered By: juanchopanza

From docs:

list.reverse()

Reverse the elements of the list, in place.

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. This is a design principle for all mutable data structures in Python.

Answered By: Amadan

Python isn’t a functional programming language—it’s imperative. When you call the list.reverse() method you’re mutating the original list:

l = [1,2,3]
l.reverse()
print l
# prints [3, 2, 1]

A method that returns None is similar to a void function/method in the C/C++/Java world. Since list.reverse() mutates the original list, it doesn’t have anything meaningful to return, so the return value is None.

As @YS-L pointed out in his comment, you can use Python’s list slicing notation to create a reversed copy of the list:

l = [1,2,3]
print l[::-1]
# prints [3, 2, 1]
Answered By: DaoWen
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.