Augmented Assignement (was: Re: PEP scepticism)

Steve Holden sholden at holdenweb.com
Fri Jun 29 08:28:49 EDT 2001


"Bernhard Herzog" <bh at intevation.de> wrote in message
news:6qn16r7i69.fsf at abnoba.intevation.de...
> Carsten Geckeler <uioziaremwpl at spammotel.com> writes:
>
> > As mentioned above, for tuples the "+=" is completely natural, but not
for
> > lists.
>
> Funny, I mostly see it exactly the other way round. += modifies the left
> hand side in place, so it's natural for a list, but not for a tuple.
>
I suppose that depends. Given the following initialization code:

    lst = [1, 2, 3]
    tpl = (1, 2, 3)
    lstx = lst
    tplx = tpl

would you expect the same results from

    lst += ["extra"]
    tpl += ("extra", )

and

    lst = lst + ["extra"]
    tpl = tpl + ("extra", )

to be the same? In the first case lstx changes (since the value it's bound
to has mutated). In the second, it doesn't. In both cases tpl and tplx end
up bound to different values, because the immutability of tuples forced the
creation of a new object rather than the modification of an existing one.\

> I think the main problem (in as much as there actually is a problem) is
> that whether augmented assignment rebinds the left hand side depends on
> the type of object, i.e. whether the object implements the appropriate
> methods, which is very different from normal assignment which always
> rebinds.
>
This is the feature most likely to cause confusion in beginners, but then
one side or the other of this particular equation is always going to be
confusing to someone who's not used to working with Python-style name
bindings...

regards
 Steve
--
http://www.holdenweb.com/






More information about the Python-list mailing list