4

I always assumed that

x += y

was just a shortcut for

x = x + y

But it seems that's not the case for lists:

x = []

x2 = x

print x is x2
True

x += [2]

print x is x2
True

x = x + [2]

print x is x2
False
matiascelasco
  • 1,145
  • 2
  • 13
  • 18
  • Note that the results of both operations *compare* equal, but the in-place version does not assign to a new list. – rlbond Aug 19 '15 at 17:36

1 Answers1

10

This happens because x += y is not just a shortcut of x = x + y.

There is a Python magic method named __iadd__ that can replace the default behavior of += when the left-value of the operator is an object which belongs to the class we are defining.

So, it seems that the Python built-in type list implements __iadd__ as follows:

def __iadd__(self, other):
    for x in other:
        self.append(x)

This way, since the default behavior of += is been avoided, no new list is created and that's why x points to the same object after x += [2] but no after x = x + [2]. In the later, a new list is created and assigned to the variable.

matiascelasco
  • 1,145
  • 2
  • 13
  • 18
  • 4
    I would imagine this behavior is intentional. It allows you to distinguish between the two operations by merely changing the operator; and, if I might say so, the usages seem intuitive. – Robert Harvey Aug 19 '15 at 02:55
  • Intuitive?!?!! One of the worst arguments around for *any* language/software feature. About as useful as arguing that one computing paradigm is more "natural" than another. It may have been intuitive for you, but clearly not for the OP. To me, this is a silly, silent gotcha waiting to catch people out. – itsbruce Aug 19 '15 at 16:49
  • 2
    `def __iadd__(self, other): self.extend(other); return self`, actually. – Martijn Pieters Aug 19 '15 at 17:31