问题
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.
回答1:
reverse
modifies the list in place and returns None
. If you do
l.reverse()
print l
you will see your list has been modified.
回答2:
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]
回答3:
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
回答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
.
来源:https://stackoverflow.com/questions/19299563/list-reverse-is-not-working