Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The usage of reverse() in Python [duplicate]

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.

like image 243
Ren Avatar asked Dec 19 '22 03:12

Ren


2 Answers

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.

like image 196
Paul Rooney Avatar answered Dec 21 '22 23:12

Paul Rooney


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)
like image 34
14 revs, 12 users 16% Avatar answered Dec 22 '22 00:12

14 revs, 12 users 16%