list operation '+= ' or assignment problem

Steve Holden sholden at holdenweb.com
Thu Jan 4 08:01:41 EST 2001


JoeSmith <JoeSmith at BogusAddress.bogusaddress.com> wrote in message
news:fXV46.83554$A06.2935629 at news1.frmt1.sfba.home.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).
>
Correct.  Lists are mutable, strings are not.

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

The statement above modifies the object bound to l in-place, which means
that any other variables bound to the same object see the change reflected
in their values too.

> >>> print l1
> [0, 1, 2, 3]

As expected.

> >>> print l
> [0, 1, 2, 3]
> >>>
>
> example 2:
> >>> s1 = "1"
> >>> s2 = "2"
> >>> s = s1
> >>> s += s2

Since strings are not mutable, the object bound to s cannot be modified
in-place, so a new string is created and bound to the name s.  Other names'
bindings remain unchanged.

> >>> print s1
> 1
> >>>
>
As expected.

There was a lot of discussion about the semantics of augmented assignment
maybe three months ago.  I argued that this behavior was counter-intuitive
to beginners.  It appeared that this was just a repetition of the arguments
when the behavior was originally discussed, and that augmented assignment
was always intended to allow in-place modification of mutable objects as an
optimization.  The BDFL has spoken!

regards
 Steve







More information about the Python-list mailing list