[Tutor] Duplicating lists in variables?

Ivan Van Laningham ivanlan@callware.com
Fri, 17 Sep 1999 13:16:04 -0600


Hi All--

Warren 'The Howdy Man' Ockrassa wrote:
> 
> 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?
> 

Try this:


foo = [1,2,3]
bar = foo[:]

print foo
print bar
bar.append(4)
print foo
print bar


<life-is-easier-than-you-think>-ly y'rs,
Ivan
----------------------------------------------
Ivan Van Laningham
Callware Technologies, Inc.
ivanlan@callware.com
ivanlan@home.com
http://www.pauahtun.org
See also: 
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
----------------------------------------------