Sunday, 5 June 2016

python - Why list reverse returns Null?




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?


Answer




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)


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...