More than one element of list changing when only one should be

Peter Otten __peter__ at web.de
Mon Jun 9 03:48:03 EDT 2008


Chuckk Hubbard wrote:

> I can't think of any reason these lines:
> 
> self.regionlist[self.hregion][0] = self.curnum
> self.regionlist[self.hregion][1] = self.curden
> self.regionlist[self.hregion][3] = self.octave11 = self.yadj
> 
> should change self.regionlist[0] AND self.regionlist[2] in the same
> call, but they do.  Also, if I add more regions in series, they all
> update each other.

The likely explanation is that regionlist[0] and regionlist[2] are actually
the same list. Throw in a 

print self.regionlist[0] is self.regionlist[2] 

to verify. The two most common reasons for that:

class A:
   items = [] # class attribute, shared between all instances


def f(items=[]): # default argument, shared between all calls
                 # without explicit items argument
    return items

Peter



More information about the Python-list mailing list