[Tutor] Duplicating lists in variables?

Corran Webster cwebster@nevada.edu
Fri, 17 Sep 1999 12:09:12 -0700 (PDT)


> I don't see an immediate way around this one.
> 
>   >>> foo = [1,2,3]
>   >>> bar = foo
>   >>> bar
>   [1, 2, 3]
>   >>> bar.append(4)
>   >>> bar
>   [1, 2, 3, 4]
>   >>> foo
>   [1, 2, 3, 4]
> 
> When I append bar, IOW, foo gets modified too. Is there a way for me to
> actually *duplicate* a list or am I stuck just propagating pointers to
> one list?

One way is:

bar = foo[:]

which copies the entire list by taking it as a slice.  For more complex
mutable objects, you might take a look at the copy module:

import copy

bar = copy.copy(foo)      # same as above but works for any mutable object

bar = copy.deepcopy(foo)  # will copy any mutable objects contained in foo
                          #  and any mutables contained in _them_, and so
                          #  on...

Regards,
Corran