Augmented Assignement (was: Re: PEP scepticism)

Bruce Sass bsass at freenet.edmonton.ab.ca
Thu Jun 28 18:54:18 EDT 2001


On Fri, 29 Jun 2001, Carsten Geckeler wrote:
> On Thu, 28 Jun 2001, Bruce Sass wrote:
<...>
> > >>> a = [1,2]
> > >>> a
> > [1, 2]
> > >>> id(a)
> > 135320620
> > >>> a += [3,4]
> > >>> id(a)
> > 135320620
>
> For list the following two statements are NOT the same:
> 	a += [1, 2]
> 	a = a + [1, 2]

This wasn't even on my radar; a path to explaining how adding
something to an immutable object works, and why there would be a
discrepancy between += with tuples and list because of it, was though.

<...>
> Of course, this is (more or less) explained in the reference (and
> probably somewhere else, too), but it is somehow confusing that
> 	a += [3, 4]
> is more like
> 	a.extend([3, 4])
> than
> 	a = a + [3, 4]

heh. I always think this last one should give me [1, 2, [3, 4]]

This confuses me...
>>> a
[1, 2]
>>> a = a + (3, 4)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: can only concatenate list (not "tuple") to list
>>> a += (3, 4)
>>> a
[1, 2, 3, 4]

<...>
> As mentioned above, for tuples the "+=" is completely natural, but not for
> lists.

Lists do seem to be a little (uhm) quirky at times.


- Bruce





More information about the Python-list mailing list