[Tutor] Tuples, Dictionarys and mutable vs. immutable

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


On Sun, Feb 25, 2001 at 10:35:33PM -0800, Sheila King wrote:
> OK, another question.
> 
> Here is something I ran on IDLE. A fresh session:
> 
> 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
> >>> x=1
> >>> id(x)
> 8400864
> >>> y=1
> >>> id(y)
> 8400864
> >>> del x
> >>> del y
> >>> z = 1
> >>> id(z)
> 8400864
> >>> id(1)
> 8400864
> >>> id('a')
> 8532752
> >>> id(('a', 'b', 'c'))
> 8756556
> >>> z=('a', 'b', 'c')
> >>> id(z)
> 8756556
> >>> 
> 
> OK, question:
> 
> See how, even before I assigned the tuple ('a', 'b', 'c') to any variable, in
> fact, the first time I mentioned it in the shell session, it already had an
> id(). Which, means it had a memory location.
> 
> Does Python create that location and assign the object to it as soon as I
> mention it? Was that memory assignment made when I typed:
> >>> id(('a', 'b', 'c'))

Yes. Once you mention ('a','b','c') in some expression, it needs a memory
location, since it needs to exists somewhere before you do further
computation on it (like give it as an argument to id(), in this case).

However, right after the expression, nothing refers to the tuple anymore,
and the memory space is freed. 'z' simply takes the same memory, so the ids
are accidentally equal.

Actually, that is how it works in a normal program. Try typing
print id((1,2))
z=(3,4)
print id(z)

into some file, and then run "python filename". For me, that prints the same
number twice. However, it doesn't work in the interactive interpreter:
apparently it keeps a reference to the old tuple around somewhere in its
internals, or something like that...

-- 
Remco Gerlich