Deeper copy than deepcopy
Gary Herron
gherron at islandtraining.com
Tue Oct 27 18:16:15 EDT 2009
Scott Pakin 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?
>
> Thanks,
> -- Scott
>
Try this:
>>>
>>> d = [1,2,3]
>>> r = [[x for x in d] for i in range(3)]
>>> r[1][2] = 999
>>> r
[[1, 2, 3], [1, 2, 999], [1, 2, 3]]
Gary Herron
More information about the Python-list
mailing list