Augmented Assignement (was: Re: PEP scepticism)

Bruce Sass bsass at freenet.edmonton.ab.ca
Thu Jun 28 17:03:14 EDT 2001


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

>>> a = 1,2
>>> b = a
>>> a, b
((1, 2), (1, 2))
>>> id(a), id(b)
(135055732, 135773292)
>>> a = a + 3,4
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: can only concatenate tuple (not "int") to tuple
>>> a = a + (3,4)
>>> a
(1, 2, 3, 4)
>>> id(a)
135523340
>>> a += 5,6
>>> a, b
((1, 2, 3, 4, 5, 6), (1, 2))
>>> id(a), id(b)
(135746564, 135773292)

> 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

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


- Bruce





More information about the Python-list mailing list