# [Tutor] Tuples, Dictionarys and mutable vs. immutable

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 26 Feb 2001 01:39:21 -0800 (PST)

```On Sun, 25 Feb 2001, Sheila King wrote:

> OK, it gets better and better. Now explain this:
>
> >>> mytuple
> 'b'
> >>> mylist =['a', 'b', 'c']

Ok, we have this picture so far:

mytuple -----> 'b'
mylist  -----> ['a', 'b', 'c']

> >>> type (mylist)
> <type 'list'>
> >>> id(mylist)
> 11519964

Wait, let me remind myself what id does:

###
>>> print id.__doc__
id(object) -> integer

Return the identity of an object.  This is guaranteed to be unique among
simultaneously existing objects.  (Hint: it's the object's memory
###

Ah, ok, so that means that our picture is too simplified; there's actually
a memory position involved here:

mytuple -----> 'b' (don't know yet)
mylist  -----> ['a', 'b', 'c'] (at position 11519964)

> >>> id (mytuple)
> 8532608

Ok, so our picture is now:

mytuple -----> 'b' (at position 8532608)
mylist  -----> ['a', 'b', 'c'] (at position 11519964)

> >>> mylist = mytuple

Now its:

mytuple -----> 'b' (at position 8532608)
mylist  --------^

You might be wondering where the value ['a', 'b', 'c'] just went to.
Because we've just cut off the only reference to that value, it just
"floats away".  Nice idylic picture.  Too bad we have to call it GARBAGE
COLLECTION.  *grin*

> >>> type (mylist)
> <type 'string'>
> >>> id (mylist)
> 8532608

And the picture above reflects why it gives us these results.  The thing
that might be confusing is that there's a separation between the "name"
(reference) of a thing and its "value".  Python will let us put hundreds
of names, all directed to the same value.

###
>>> a = ['some value in a mutable list']
>>> b = a
>>> c = b
>>> a, b, c
(['some value in a mutable list'], ['some value in a mutable list'],
['some value in a mutable list'])
###

and by changing that mutable value, we'll see its effect across the board:

###
>>> a[0] = 'changed!'
>>> a, b, c
(['changed!'], ['changed!'], ['changed!'])
###

Side note: one thing you might have noticed is that when we take the id()
of numbers:

###
>>> x = 5
>>> y = 5
>>> id(x), id(y)
(135823832, 135823832)
###

it appears that we're getting the same value.  No shock yet; why shouldn't
it?  But here's something weird:

###
>>> u = 3000
>>> v = 3000
>>> id(u)
135942320
>>> id(v)
135942368      ## They're different!
###

Try to think of a reason why this happens.  Hint: there's a point in which
this strangeness triggers, and it's somewhere between 5 and 3000.  *grin*

```