Augmented Assignement (was: Re: PEP scepticism)

Carsten Geckeler uioziaremwpl at spammotel.com
Thu Jun 28 18:02:24 EDT 2001


On Thu, 28 Jun 2001, Bruce Sass wrote:

> On Thu, 28 Jun 2001, Paul Prescod wrote:
>
> > I think Python has been getting better and better as time goes on. But I
> > do have a concern about augmented assignment. How can a newbie
> > understand that tuples are "immutable" if this works:
> >
> > mytuple += (foo,bar)
>
> Ya, ok, it was a rhetorical question <shrug>
> maybe this sequence would help explain it to someone...
[snip]

I don't see your point.  With a tuple "a" the following two statements are
exactly the same:
	a += (1, 2)
	a = a + (1, 2)

> > Worse, once they've learned that this does NOT affect other references
> > to mytuple they are bound to be confused by
> >
> > mylist += [foo, bar]
> >
> > which does!
>
> >>> 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]

Let's see an example.

>>> a = [1, 2]
>>> b = a
>>> a = a + [3, 4]
>>> a
[1, 2, 3, 4]
>>> b
[1, 2]

Now, starting with the same first two statements (a=[1,2]; b=a):

>>> a += [3, 4]
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]

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]
.

> > I've seen this confusion already -- in a draft of a book no less.
>
> Once they see that "adding" tuples creates a new object (it has to,
> tuples are immutable), and the alternative is manually concatenating
> the tuples yourself...
>
> ...what was a wart becomes a feature.

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

Cheers, Carsten
-- 
Carsten Geckeler





More information about the Python-list mailing list