Unexpected behavior with list.append

I worked with my interpreter to figure out the behavior of the Python method append()

and found:

In [335]: b = [].append(1)

In [336]: b

In [337]: 

In [337]: b = [].append('1')

In [338]: b

      

Which puzzles me, because I thought that whenever we call append()

in a list, we add new objects to the end, so it should not be called append()

on an empty list (like what I did above) the same result that I could achieve with:

In [339]: b=[] 

In [340]: b.append(1)

In [341]: b
Out[341]: [1]

      

I may have a misconception here, so please correct me if I am wrong.

+3


source to share


2 answers


Which puzzles me because I thought that whenever we call append()

on the list, we add new objects to the end

It is right. But you're forgetting that append()

(like most methods that mutate objects) it always returns None

in Python because it works in place. So, doing this:

b = [].append(1)

      

matches:



b = None

      

1

technically added to a list []

, but there is no way to access that list after the call append()

, as it is b

assigned to the return value of the method call.

The second example works great simply because you don't reassign b

and thereby lose the reference to the list object.

+5


source


append

is a method that returns nothing. So the call ls.append(1)

will add 1

to the end ls

, but ls.append(1)

has no actual value. Therefore, the installation b = [].append('1')

installs b

in None

.



+2


source







All Articles