pitfall for your amusement
Erik Max Francis
max at alcyone.com
Tue Nov 12 16:27:12 EST 2002
Gustavo Niemeyer wrote:
> > This note is mostly for entertainment purposes.
> >
> > >>> x = (1, 2, 3)
> [...]
> > >>> x += (4, 5, 6)
>
> Hey, shouldn't this raise an exception?
No, not anymore than
x = 1
x += 1
should. += (and the other assignment combination operators) will use
the same object when it's mutable, but actually does a rebinding when
immutable. For instance,
L = [1, 2, 3]
L += [4, 5, 6]
is the equivalent of
L = [1, 2, 3]
L.extend([4, 5, 6])
but
x = 1
x += 1
actually does the equivalent of
x = 1
x = x + 1
Since tuples are immutable, using the += operator on them does the
latter (resulting an a rebinding), not the former.
--
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/ \ If a thing is worth doing, then it is worth doing badly.
\__/ G.K. Chesterton
ZOE / http://www.alcyone.com/pyos/zoe/
A simple Python OpenGL rendering engine.
More information about the Python-list
mailing list