3

Possible Duplicate:
What does plus equals (+=) do in Python?

I noticed a strange problem:

    l1 = ['1', '2', '3']
    l2 = l1

    item = l2.pop(0)
    # the pop operation will effect l1
    print l1

    l2 = l2 + [item]
    # why "l2 = l2 + [item]" does't effect l1 while "l2 += [item]" does.
    print l2
    print l1

The output is:

['2', '3']
['2', '3', '1']
['2', '3']

But if i change l2 = l2 + [item] into l2 += [item], the output will be:

['2', '3']
['2', '3', '1']
['2', '3', '1']
Community
  • 1
  • 1
redice
  • 8,437
  • 9
  • 32
  • 41

2 Answers2

6

+ and += are different operators woth different internal meaning as described here.

l2 = l1 + x calls l2 = l1.__add__(x), if that doesn't work it calls x.__radd__(l1). Both should return a new object forming the result of the operation, independent from the old one, thus not affecting l1.

l2 += x calls l2 = l2.__iadd__(x) ("augmented assignment"), and only if this doesn't work, falls back to l2 = l2 + x as described above.

With numbers, both are the same, because they are immutable and thus cannot be modified with +=, while on lists, + returns a new object while += modifies the left hand side one.

As the object behind l2 is modified and l1 refers the same object, you notice the change on l1 as well.

glglgl
  • 89,107
  • 13
  • 149
  • 217
1

After you assign l2 = l1, l2 is the same as l1. The following pop operation affects both l1 and l2 as they are the same.

l2 = l2 + [item] creates a new list. So l2 is now a different object.

l2 += [item] modifies l2 inplace. So l2 points to the same thing as l1.

Interactive visualization of your code execution:

Some relevant links:

ovgolovin
  • 13,063
  • 6
  • 47
  • 78
  • Note that the OP didn't ask for an explanation. He said he "noticed a problem"... – phant0m Nov 11 '12 at 09:35
  • @phant0m Right. Because he didn't understand how things work. So explaining them is the thing to do. – glglgl Nov 11 '12 at 09:48
  • 1
    @glglgl That's a weird way to put you don't understand something... but still, he did observe what the differences are, and the accepted answer doesn't explain any more than that. Yours on the other hand actually provides more detail. – phant0m Nov 11 '12 at 09:51
  • 1
    @phant0m This question seems to be a candidate for closing! So I just answered for the question to not be left without the answer (I sometimes find better answers to my own problems in the closed questions here) – ovgolovin Nov 11 '12 at 09:57
  • @phant0m If I don't realize I didn't understand something right I might consider things a problem which really aren't... – glglgl Nov 11 '12 at 10:00