Alex
Alex

Reputation: 4264

Strange thing happens with append

Why does the following code make a equal to "None":

a = [1]
a = a.append(0) if len(a) == 1 else a

This happens in both Python 2 and 3.

Upvotes: 0

Views: 40

Answers (2)

9000
9000

Reputation: 40894

It just so happens that list.append does not return the list. It mutates it and returns nothing (None).

In your case, a = a +[0] if len(a) == 1 else a would work. But the following is simpler: if len(a) == 1: a.append(0).

Upvotes: 1

Jim K
Jim K

Reputation: 13790

append() does not return a value. Just do this:

a = [1]
if len(a) == 1:
    a.append(0)

Upvotes: 3

Related Questions