[Tutor] Python oddity

Tiger12506 keridee at jayco.net
Fri Feb 29 03:02:52 CET 2008


> i'd like to know, too. my take so far is
>
> * don't make any copies if you can avoid doing so,
> * make shallow copies if need be,
> * make deep copies only if you can't think of any
> other way to accomplish what you're up to.

Yep. That's pretty much it, for space reasons, mostly. Imagine a list (or 
any other mutable object) as a table of contents. When you first create a 
list, all of the contents are stored in memory and the list becomes the 
table of contents. Now when you assign this table of contents to a new 
variable, no significant extra memory is stored. It's basically just another 
name (rose by any other name still smells as sweet) for the same table of 
contents.

Now imagine that to save space, instead of the table of contents being only 
references to 'chapters' (objects), that whenever an immutable object is 
added to a list, it is written directly on the table of contents page. 
Mutable objects (they can be changed) are still just references to 'page 
numbers' in the actual contents of memory.

Now when you copy a list (by default a shallow copy), you are really only 
copying the table of contents onto a different sheet of paper. This includes 
the slice, copy.copy, and the list() methodologies described. You see now 
how immutable objects have to become new copies because they are written 
directly on the table of content page, right? Shallow copying is less 
preferable to an alias (another name) because extra space is needed to store 
the extra copy of the table of contents. However, all mutable objects 
contained within the list will not be copied, and the two table of contents 
will still refer to the same 'page numbers' in the same 'book'.

Finally, the deep copy. This recursively (is it true recursion???) runs 
through the table of contents of a list and makes a copy of each 'page' in 
the 'book' and constructs a completely new and seperate entity. 



More information about the Tutor mailing list