1

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?

user3654650
  • 5,283
  • 10
  • 27
  • 28

3 Answers3

8

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)

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
4

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.

Community
  • 1
  • 1
Amadan
  • 191,408
  • 23
  • 240
  • 301
2

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]
Community
  • 1
  • 1
DaoWen
  • 32,589
  • 6
  • 74
  • 101