I used two different ways to create a reverse list.
The first way:
>>> a=list(range(3))
>>> a.reverse()
>>> print(a)
[2,1,0]
The second way:
>>> a=list(range(3)).reverse()
>>> print(a)
None
Why does the second way does not work?Thanks for any help.
It fails because reverse
changes the list in place (i.e. it does not create a new list) and like most functions that operate in place it returns None
.
In your first example
a=list(range(3))
a.reverse()
print a
It works fine as you capture a
as the return value from list(range(3))
, which returns a list
. You then reverse that list in place and print it. All fine!
In your second example
a=list(range(3)).reverse()
print(a)
a
is equal to the return value of reverse()
(not list(range(3))
).
reverse
is called on a temporary list and returns None
, which is the value assigned to a
.
Why does the second way does not work?
.reverse()
doesn't return a list (it returns None
). It modifies the argument you pass into it.
You need to do it the same as the first method:
a=list(range(3))
a.reverse()
print(a)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With