[Tutor] Copying a list?

Lloyd Kvam pythontutor at venix.com
Wed Aug 27 18:58:51 EDT 2003


import copy
b = copy.copy(a)

This is a "shallow" copy.  b is a new list, but contains the same
elements as a.  For your example with numeric (immutable) elements
this is fine.  If a contains mutable elements, and you wish b to
have COPIES of those mutable elements then:

b = copy.deepcopy(a)

This handles the case where:
a = [ [], [] ,[], ]
after the deepcopy, b will have its own set of empty lists.

Zak Arntson wrote:

> I feel pretty silly asking this, but is there a way to quickly copy a
> list? I'd love to be able to type:
> 
> ###
> 
>>>>a = [1,2,3]
>>>>b = a
> 
> ###
> 
> But that's a pass-by-reference. The quickest thing that comes to mind is:
> 
> ###
> 
>>>>a = [1,2,3]
>>>>b = [i for i in a]
> 
> ###
> 
> Which is okay, but not as obvious as, say:
> 
> ###
> 
>>>>a = [1,2,3]
>>>>b= a.__copy__()
> 
> ###
> 
> or something. Am I forgetting something?
> 
> ---
> Zak Arntson
> www.harlekin-maus.com - Games - Lots of 'em
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582




More information about the Tutor mailing list