5

I though that a += b is just a shortcut for a = a + b. It seems it is not quite. Here's an example:

>>> a = [1, 2, 3]
>>> b = a
>>> b += [4, 5, 6]
>>> b
[1, 2, 3, 4, 5, 6]
>>> a # is also changed
[1, 2, 3, 4, 5, 6]

But this works as expected:

>>> a = [1, 2, 3]
>>> b = a
>>> b = b + [4, 5, 6]
>>> b
[1, 2, 3, 4, 5, 6]
>>> a # not changed
[1, 2, 3]

Now, I understand that when I do b = a, b references the same list as a does, and if I do some operations on b, they automatically "apply" to a (since they both point to the same list, and that when I do b = b + [4, 5, 6] a new list is created and then assigned to b, but my question is...why this distinction? I mean, shouldn't a += b be a shorthand for a = a + b? This is what one would have expected...What's the logical explanation for this?

linkyndy
  • 17,038
  • 20
  • 114
  • 194

1 Answers1

1

The a+=b is a shortcut for a.extend(b), not a=a+b .. which, as you've said, creates a new list.

eduffy
  • 39,140
  • 13
  • 95
  • 92
  • 3
    Probably would be good to point that this answer only applies when `a` is a `list`, not in general. – lanzz Feb 06 '14 at 13:50
  • `+=` is not a shortcut; rather, its implementation happens to coincide with that of `extend`. – chepner Feb 06 '14 at 13:51
  • This is what I was asking actually. **Why** is this the intended behaviour for lists? Why it has been opted to work like this? – linkyndy Feb 06 '14 at 13:52
  • This is the "usual" expected behavior of those operators. `+=` modifies the object in place, `+` creates a new object that is the "sum" of both. – dornhege Feb 06 '14 at 13:54
  • 1
    In the general case, `a += b` is a shortcut for `a.__iadd__(b)`, and `a + b` is a shortcut for `a.__add__(b)`. That is how the language works. The intention is to separate immutable operations and in-place mutations. `__add__` *should* be written so that the result is a new object which is the 'sum' of the original operands (whatever 'sum' means in terms of the class), while `__iadd__` *should* modify the left-hand side operand 'in-place' to take the sum as its value. Both have their uses; in-place modification may save space, while immutability may benefit (for instance) parallelization. –  Feb 06 '14 at 13:57
  • This is the kind of answer I was looking for! Thank you. – linkyndy Feb 06 '14 at 13:59