[Tutor] Tuples, Dictionarys and mutable vs. immutable

Sheila King sheila@thinkspot.net
Sun, 25 Feb 2001 23:37:53 -0800

On Mon, 26 Feb 2001 08:09:58 +0100, Remco Gerlich <scarblac@pino.selwerd.nl>
wrote about Re: [Tutor] Tuples, Dictionarys and mutable vs. immutable:

: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 :)

Yes, I think this is extremely important, and I need to get it. Thanks for
your examples. They are very helpful. Thanks for the invitation to ask
questions. I think I will!

OK, an immutable type, such as a tuple, cannot be changed. Once created, it is
assigned a memory location, and if I do something like this:

>>> z=(1,2)
>>> z+=(3,4)
>>> print z
(1, 2, 3, 4)

The tuple I end up with is not the same as the one I started with. It has a
different memory location, and a different id(). However, based on what Remco
wrote earlier in this thread, I'd guess that the memory for the tuple (1,2)
has now been freed, if it has no name assigned to it, and I can now assume
that the operating system now has access to that memory location again?

OK, but now the mutable types:
lists and dictionaries.

I know a dictionary has a copy method, so that I can have a new dictionary
with same contents, without having to worry about modifying the contents of
the original:

>>> dict={1:"one", 2:"two"}
>>> dict
{2: 'two', 1: 'one'}
>>> id(dict)
>>> dict2 = dict.copy()
>>> id(dict2)

What about lists? So far as I can determine, they do not have a copy method,
and I would be modifying the "original" list, if I tried to assign it to a
second variable name and then make modifications to that one, without
modifying the original.

What is the proscribed method for handling lists so that one is a copy that
can be modified without changing the original version?

Sheila King