[Tutor] Tuples, Dictionarys and mutable vs. immutable

Remco Gerlich scarblac@pino.selwerd.nl
Mon, 26 Feb 2001 08:09:58 +0100


On Sun, Feb 25, 2001 at 08:30:59PM -0800, Sheila King wrote:
> OK, now I'm really confused.
> 
> I don't really "get" the difference yet, between mutable and immutable types,
> but I figured I would eventually get it. But at least I thought I understood
> that an object could not change its type or its id. At least I thought I
> understood that.
> 
> Then, explain this from my Python IDLE:
> Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> IDLE 0.6 -- press F1 for help
> >>> mytuple = 'a', 'b', 'c'
> >>> mytuple
> ('a', 'b', 'c')
> >>> type (mytuple)
> <type 'tuple'>
> >>> mytyple = 'b'
> >>> mytyple
> 'b'
> >>> type (mytyple)
> <type 'string'>
> >>> mytuple = mytyple
> >>> type (mytuple)
> <type 'string'>
> >>>  
> 
> mytuple is originally a tuple. And then I end up changing it to a string? I
> thought this was not possible.

The key thing to remember is that 'mytuple' is just a name for some object.
When you assign to it, it becomes a name for another object.

If that object is immutable, then *it* can't be changed. But you can always
give the name to something else.

The id() of an object never changes; the object gets an id when it's created
and that is that.

Simple assignment never changes an object, so it doesn't care if something
is mutable or not. It gives a name to an object.

The exception is when you assign to something *inside* an object, like x[3]=4
(when x is a list or dictionary). The object 4 isn't changed, but the object
x is, since one of its contents now refers to something else.

Therefore, with tuples you can't do mytuple[0]=4, but you can say mytuple=4
(the old tuple object is simply discarded when nothing else refers to it).

>>> x = [1,2]
>>> id(x)
136158892
>>> x[0]=3   # x is mutable, so we can change it
>>> x
[3, 2]
>>> id(x)
136158892    # x is still the same object
>>> y=x      # now y and x are names for the same object
>>> y.append(4) # again, the object is changed
>>> x
[3, 2, 4]    # So x is changed as well, after all they're the same


>>> x = (1,2) # Now x is immutable
>>> id(x)
136049924
>>> x[0]=3    # Error! x is immutable so can't assign to internals
>>> y=x       # Now x and y are names for the same object
>>> x = x+(3,4)
>>> x
(1,2,3,4)
>>> y
(1,2)
>>> id(y)
136049924     # Still the old object
>>> id(x)
136126740     # New object!

Now y is not changed, since when we did "x = x+(3,4)", x became a name for a
*new* object, namely the result of the addition.

I believe this is the key thing to understand about Python. Ask more
questions if you don't get it yet :)

-- 
Remco Gerlich