-2

Why does the output for following code differs in python,

>>> A = [1,2,3]  
>>> B = A  
>>> B += [4]  
>>> print A,B  
Output: A = [1,2,3,4] , B = [1,2,3,4]  

But if we replace B += [4] to B = B + [4] the output changes to:

>>> A = [1,2,3] , B = [1,2,3,4]

Please explain.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
rhn89
  • 362
  • 3
  • 11

1 Answers1

1

+= is augmented addition; for mutable types it alters the object in place.

You would get the same effect if you did:

B.extend([4])

Assigning B to A does not create a copy, so B and A refer to the same object, and any changes to that object are visible through both references.

When, however you use B = B + [4] you create a new list object, and rebind B to that new object. Because a new list object is created, the original list object (previously referenced by B and still referenced by A) is unaffected.

In effect, by using straight concatenation, you created a shallow copy of the original list object.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343