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 ca
l += ...
is actually calling object.__iadd__(self, other)
and modifies the object in-place
when l
is mutable
The reason (as @DeepSpace explains in his comment) is that when you do l += {'a': 2}
the operation updates l
in place only and only if l
is mutable. On the other hand, the operation l + {'a': 2}
is not done in place resulting into list + dictionary -> TypeError
.
(see here)
l = [1]
l = l.__iadd__({'a': 2})
l
#[1, 'a']
is not the same as +
that calls object.__add__(self, other)
l + {'B': 3}
TypeError: can only concatenate list (not "dict") to list