Python assignment operator differs from non assignment

前端 未结 2 1812
無奈伤痛
無奈伤痛 2021-01-01 14:15

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         


        
2条回答
  •  别那么骄傲
    2021-01-01 15:00

    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
    

提交回复
热议问题