[Tutor] Tuples, Dictionarys and mutable vs. immutable

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

On Sun, Feb 25, 2001 at 11:37:53PM -0800, Sheila King wrote:
> 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?

list1 = [1,2,3]

list2 = list1[:]  # Use slice notation to get the whole list
import copy
list2 = copy.copy(list1)

Now list2 is a so-called "shallow" copy of list1, the things in the list are
copied, but those may again be the same objects (think lists in lists).
If you want to recursively copy them all, use copy.deepcopy().

Remco Gerlich