20

I honestly just don't understand why this is returning None rather than a reversed list:

>>> l = range(10)
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print l.reverse()
None

Why is this happening? According to the docs, I am doing nothing wrong.

Ryan Saxe
  • 17,123
  • 23
  • 80
  • 128

4 Answers4

36

reverse modifies the list in place and returns None. If you do

l.reverse()
print l

you will see your list has been modified.

mdml
  • 22,442
  • 8
  • 58
  • 66
  • 2
    Sure, but what is the reason for not just returning the list too instead of `None`? Since it's just a reference and not a copy of the list, it can't be too expensive... – KasparJohannes Apr 06 '21 at 20:28
9

L.reverse() modifies L in place. As a general rule, Python builtin methods will either mutate or return something but not both

The usual way to reverse a list is to use

print L[::-1]

reversed(L) returns a listreverseiterator object which is fine for iterating over, but not so good if you really want a list

[::-1] is just a normal slice - the step is -1 so you get a copy starting from the end and ending with the start

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
6

list.reverse() reverses the list in place. It doesn't return the reversed list. For that, use reversed() function:

print reversed(l)

Or just use the extended slice notation:

print l[::-1]
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
4

The docs say

list.reverse() : Reverse the elements of the list, in place.

in place means the original list gets changed, rather than returning a new list, so the return you ask it to print is None.

doctorlove
  • 18,872
  • 2
  • 46
  • 62