[Tutor] Cloning lists to avoid alteration of original list
Daniel Ehrenberg
littledanehren at yahoo.com
Tue Jan 13 20:25:23 EST 2004
Dear All,
> I am having problems with cloning a list in such a
>
> way that it alters one list but not the other. The
> list for the new
> area should have "4"
>
> I have tried the standard procedure of taking a
> slice of the list,
> renaming it and operatiing on that, but to no avail.
> One issue that
> may make a difference is that I am taking a slice of
> a longer list,
> rather than the complete list.
>
> Here is the section of code, which is a class. I
> have tried cloning
> the two lists outside of the class, as well as
> within the class, but
> the program always carries out the changes to both
> lists. I apologize
> for the length of the extact. If further information
> is needed,
> please let me know.
> Thanks in advance,
> Al
Try cloning the list using deepcopy. Here's an
example:
>>> from copy import deepcopy
>>> x = range(3)
>>> x
[0, 1, 2]
>>> y = x #just links it
>>> x.append(3)
>>> x
[0, 1, 2, 3]
>>> y
[0, 1, 2, 3]
>>> z = deepcopy(x)
>>> z
[0, 1, 2, 3]
>>> x.append(4)
>>> x
[0, 1, 2, 3, 4]
>>> y
[0, 1, 2, 3, 4]
>>> z
[0, 1, 2, 3]
If you could follow that, deepcopy copies the list but
it is not still linked.
Daniel Ehrenberg
__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus
More information about the Tutor
mailing list