Alex Rivera | Logout

Different behaviour for list.__iadd__ and list.__add__

Asked 2012-03-19T07:22:18.720
24

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).

Edit
Report

1 Answer

5

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

answered 2012-03-19T07:26:05.227

Your Answer