Deeper copy than deepcopy

Scott Pakin scott+clp at pakin.org
Tue Oct 27 16:01:52 EDT 2009


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?

Thanks,
-- Scott



More information about the Python-list mailing list