Different behaviour for list.__iadd__ and list.__a

2019-01-02 16:16发布

consider the following code:

>>> x = y = [1, 2, 3, 4]
>>> x += [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4, 4]

and then consider this:

>>> x = y = [1, 2, 3, 4]
>>> x = x + [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4]

Why is there a difference these two?

(And yes, I tried searching for this).

标签: python list
2条回答
何处买醉
2楼-- · 2019-01-02 16:27

__iadd__ mutates the list, whereas __add__ returns a new list, as demonstrated.

An expression of x += y first tries to call __iadd__ and, failing that, calls __add__ followed an assignment (see Sven's comment for a minor correction). Since list has __iadd__ then it does this little bit 'o mutation magic.

查看更多
爱死公子算了
3楼-- · 2019-01-02 16:33

The first mutates the list, and the second rebinds the name.

查看更多
登录 后发表回答