Search code examples
pythonassignment-operator

Python assignment operator differs from non assignment


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


Solution

  • 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