Unexpected result for list operator "+="

Joe Smith JoeSmith at bogusaddress.com
Thu Jan 4 02:31:35 EST 2001


I unexpectedly get l1 modified by doing "l += l2" (see example 1).  I take
it is because l and l1 point to the same object.  If I use the string type
instead of the list type, I don't get l2 modified.  I guess that list
assignment is an assignment of the reference to the object and it does not
copy the object.  Where as a string object gets copied (see example 2).

example 1:
>>> l1 = [0, 1]
>>> print l1
[0, 1]
>>> l2 = [2, 3]
>>> l = l1
>>> print l1
[0, 1]
>>> print l
[0, 1]
>>> l += l2
>>> print l1
[0, 1, 2, 3]
>>> print l
[0, 1, 2, 3]
>>>

example 2:
>>> s1 = "1"
>>> s2 = "2"
>>> s = s1
>>> s += s2
>>> print s1
1
>>>





More information about the Python-list mailing list