Unexpected result for list operator "+="

Greg Jorgensen gregj at pobox.com
Thu Jan 4 03:12:02 EST 2001


"Joe Smith" <JoeSmith at bogusaddress.com> wrote in message
news:3A542778.E1BC06E3 at bogusaddress.com...
>
> 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).

You discovered the documented behavior. Assignment of immutable objects
(numbers, strings, tuples) essentially makes a copy of the object.
Assignment of mutable objects (lists, dictionaries) creates a new reference
to the original object.

To make a shallow copy of a list (rather than a new reference to the list),
the Python idiom is:

    a = [1, 2, 3, 4, 5]   # list of immutable objects
    b = a[:]  # b is a shallow copy of a

A shallow copy will do if the list (or dictionary) contains only immutable
objects. If the list (or dictionary) contains mutable objects, you will need
to make a deep copy. The copy module does this:

    import copy
    a = [ [1,2,3], [4,5,6] ]
    b = copy.deepcopy(a)

The "is" operator can test if references refer to the same object:

>>> a = [1, 2, 3, 4, 5]   # list of immutable objects
>>> b = a[:]  # b is a shallow copy of a
>>> c = b  # c references same list as b
>>> b == a
1
>>> b is a
0
>>> c == b
1
>>> c is b
1

--
Greg Jorgensen
PDXperts
Portland, Oregon, USA
gregj at pobox.com





More information about the Python-list mailing list