Reputation: 318
In a piece of code I need to copy a list and append a new value. I have found the following behaviour:
a=[]
b=[n for n in a].append('val')
print(b)
None
While, the following works as I require:
b=[n for n in a]
b.append('val')
print(b)
['val']
Any insight why it is so?
Upvotes: 2
Views: 1655
Reputation: 96016
append
modifies the list in place, it doesn't return a new list, that's why you're getting None
.
See the documentation:
.. The methods that add, subtract, or rearrange their members in place, and don’t return a specific item, never return the collection instance itself but None.
Upvotes: 4
Reputation: 33484
That is because b=[n for n in a].append('val')
does not return anything. In specific append('val')
does not return any value.
Upvotes: 1
Reputation: 33701
Method append
returns None
, because it modifies list in place, that is why b
in your first example is None
. You could use list concatenation in order to copy a list and append an element to it:
In [238]: a = [1, 2, 3]
In [239]: b = a + [4]
In [240]: b
Out[240]: [1, 2, 3, 4]
Upvotes: 2