>>> b = []
>>> c = '1234'
>>> b += c
>>> b
['1', '2', '3', '4']
>>>
What is happening here? This should not work, right? Or am I missing something obvious?
>>> b = []
>>> c = '1234'
>>> b + c
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
b + c
TypeError: can only concatenate list (not "str") to list
>>>
Then a += b
is not always equivalent to a = a + b
?
This is an answer not to the original question (which I think has been adequately answered), but to the numerous questions that have been asked in the comments about the semantics of augmented assignment (
+=
and similar operations).In a nutshell: Augmented assignment works differently for mutable types than for immutable ones.
str
,tuple
, and the numeric types, among others, are immutable. The contents of a tuple cannot be changed once it has been created, so you get this behavior:str
has the same semantics. Basically,a += b
is equivalent toa = a + b
ifa
is immutable.Most other types, including
list
, are mutable. A list's contents can be changed in place, and augmented assignment does exactly that. Hence:Whereas if the third line were replaced with
a = a + [3, 4]
, a new list would be created andb
would be[1, 2]
.For a user-defined class, the semantics depend on how it was implemented, but this is how it's supposed to be done per PEP 203.