Python List Issue

Robert Kern rkern at ucsd.edu
Sun Mar 27 04:09:53 EST 2005


Nick L wrote:
> I've hit a brick wall on something that I'm guessing is pretty simple but
> it's driving me nuts. I noticed that with python lists, generally when you
> make a copy of a list (ie, List1 = List2) List1 just becomes a reference to
> List2 and any modifications done to List1 affects List2. Ok I can live with
> this but I want to make a completely seperate copy not attached to the
> original in anyway. So then I used this method. List1 = List2[:]  .  This
> seemed to work in most situations, here I can modifiy List1 with out it
> affecting List2. But now I've run into an odd problem, and I have no idea
> why it's doing what it's doing.
> Here's some code
> 
> #some globle varibles
> bob = [[[0, 0]]]

I haven't gone through all of your code, but I suspect that the problem 
is that objects in the list (in this case, other lists) don't get copied 
  only get referenced when you do bob[:]. This is expected.

See copy.deepcopy(). It will make sure that everything gets copied and 
nothing just referenced (more or less).

http://docs.python.org/lib/module-copy.html

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter



More information about the Python-list mailing list