Deeper copy than deepcopy

Cameron Simpson cs at zip.com.au
Tue Oct 27 17:23:54 EDT 2009


On 27Oct2009 14:01, Scott Pakin <scott+clp at pakin.org> wrote:
| copy.deepcopy apparently preserves multiple references to the same object:
| 
|     $ python
|     Python 2.5.2 (r252:60911, Jan  4 2009, 17:40:26)
|     [GCC 4.3.2] on linux2
|     Type "help", "copyright", "credits" or "license" for more information.
|     >>> import copy
|     >>> d = [1,2,3]
|     >>> r = copy.deepcopy([d]*3)
|     >>> r
|     [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
|     >>> r[1][2] = 999
|     >>> d
|     [1, 2, 3]
|     >>> r
|     [[1, 2, 999], [1, 2, 999], [1, 2, 999]]
|     >>>
| 
| I wanted to wind up with r being [[1, 2, 3], [1, 2, 999], [1, 2, 3]].
| What's the right way to construct r as a list of *independent* d lists?

Well, you would need to write your own. But consider this:

  x = [1, 2]
  x.append(x)

Your deepercopy() function will explode.

Probably the best method is to pre-munge the list you pass to deepcopy:

  d = [1,2,3]
  d3 = [d]*3
  # pre-copy the multiple references
  d3deeper = [ list(d3i) for d3i in d3 ]
  r = copy.deepcopy(d3deeper)

You can see this requires special knowledge of the structure you're
copying though.
-- 
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

The mere existence of a problem is no proof of the existence of a solution.
        - Yiddish Proverb



More information about the Python-list mailing list