AKKO
AKKO

Reputation: 1081

Unexpected behavior with list.append

I was working with my interpreter to figure out the behavior of the Python append() method 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() on a list, we add new objects to its end, so shouldn't calling append() on an empty list (as what I did above) give me the the same result that I could achieve with:

In [339]: b=[] 

In [340]: b.append(1)

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

I might have a misconception here, so please correct me if I'm mistaken.

Upvotes: 3

Views: 147

Answers (2)

user2555451
user2555451

Reputation:

Which puzzles me because I thought that whenever we call append() on a list, we add new objects to its end

That is correct. But what you are forgetting is that append() (like most methods which mutate objects) always returns None in Python because it operates in-place. So, doing this:

b = [].append(1)

is the same as:

b = None

1 is technically added to the list [], but there is no way to access this list after the call to append() since b is assigned to the return value of the method call.

The second example works fine simply because you are not reassigning b and thereby losing the reference to the list object.

Upvotes: 5

msinghal
msinghal

Reputation: 288

append is a method that doesn't return anything. So calling ls.append(1) will append 1 to the end of ls, but ls.append(1) has no actual value. So setting b = [].append('1') sets b to None.

Upvotes: 2

Related Questions