Inconsistent list/pointer problem

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Feb 1 09:42:35 EST 2007


Doug Stell a écrit :
> I am having a problem with the corruption of a list. It occurs only
> the first time that I call a function and never happens on subsequent
> calls. Any suggestions would be appreciated.
> 
> I call the function, passing in a list as the input data. The function
> must manipulate and operate on a copy of that list's data, without
> altering the list in the calling routine.
> 
> def myFunc(listA):
>     listB = listA
>     work on & modify listB
>     return(listB)

return is a statement, not a function. Please remove these useless (and 
possibly harmful) parens.

> The first time this function touches listB, listA is corrupted.

It's not. It's just that you did *not* copy listA - you just made listB 
reference the same object.

> 
> I concluded that it appears that listB is still pointing at elements
> of listA 

It's even worse : both names listA and listB are pointing to the exact 
same object.

listA = ['A', 'B', 'C']
listB = listA
assert listA is listB

> and I need to force Python to reassign those pointers

s/pointers/references/

> to
> point to copies of listA's elements.

copy.deepcopy() is your friend then.




More information about the Python-list mailing list