I have face this weird behavior I can not find explications about.
MWE:
l = [1]
l += {'a': 2}
l
[1, 'a']
l + {'B': 3}
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: can only concatenate list (not "dict") to list
Basically, when I +=
python does not raise an error and append the key to the list while when I only compute the +
I get the expected TypeError
.
Note: this is Python 3.6.10
+=
and so on are called "Augmented assignments" from the PEP introducing them, PEP 203. – CyclosisWhen a is mutable, a += b updates it in-place, so there is no ambiguity: the type of a cannot change. When you do a + b, there is no reason to treat a as more deserving than b when selecting the type of the result.
– Longinus