Are tuple really immutable?

John Roth newsgroups at jhrothjr.com
Mon Dec 27 04:39:13 CET 2004


"Chris" <chris.monnet at gmail.com> wrote in message 
news:1104116589.748918.256950 at f14g2000cwb.googlegroups.com...
> Hi
>
>
> 3) In this example, is t considered mutable or not?
> "Tuple are immutable" says the doc, but:
>>>> t[0].append(0)
>>>> t
> ([1, 0], [2])
>
> The tuple is immutable but its elements can be mutable: I tend to think
> that it means that the tuple is mutable. Indeed, it changed!

Well, it did and it didn't. If you went in and did an
id() on each element, you'd discover that the actual
objects didn't change: the exact same ids were in
the exact same slots before and after. What you're
seeing is the way the str() and repr() functions print
the values of embedded objects, not the ids.

>
> 4) Even more confusing: I had the following strange result:
> (with both Python 2.3.3 and 2.4)
>>>> t[0]+=[1]
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: object doesn't support item assignment
>>>> t
> ([1, 0, 1], [2])
> There was an exception, but the list was still changed!?

I consider that an error, but I've had several people
tell me that it's the way it's supposed to be.
I simply quit trying to get the point across.
As far as I'm concerned, the behavior is simply
wrong. Since mutating the object didn't change
the id, it shouldn't try to replace the object in
the tuple.

John Roth
>
> Chris
> 




More information about the Python-list mailing list