On Monday 21 August 2006 13:40, Alan Gauld wrote: > > So when I needed to make a list of a list in the following code I > > thought no > > problem ... > > > > > > def CSV_Lines(self, csv, from_, to): > > """Returns a list of cleaned up lines from csv 'from_' line > > number 'to' line number""" > > > > clean_line = clean_csv = [] > > So clean_line is a reference to clean_csv which is a reference > to a list. That is, both variables point to the same list? > I don't think thats what you wanted... Remember that Python > variables are references to objects, in this case they both > reference the same list object.
In the past I have assigned multiple variables by var1 = var2 = 0 when one of the variables is assigned a different value, another object is created and var1 & var2 are separate. Without thinking I tried to do the same with the two lists. >>> >>> a=b=[] >>> a [] >>> b [] >>> a=[1,2,3] >>> a [1, 2, 3] >>> b [] >>> Tinkering some more I think it is the append that did it. >>> >>> a=b=[] >>> a [] >>> b [] >>> a.append([1,2,3]) >>> a [[1, 2, 3]] >>> b [[1, 2, 3]] >>> It appended to the common object and did not create a separate one ? I guess var1 = var2 = 0 is generally bad programming style ?. I keep trying to get my code more compact using list comprehension etc - in this case compact got me into trouble. I have tried looking at some open source projects eg kdissert,sbackup to get into good codeing habits but they are a bit above me. So I am learning by trying. (1 x GUI app written, a more advanced one on the way) Thanks for all your help Dave PS This is probably an impossible question but I always struggle to find names for variables - any hints ? > > > print 'clean_line ',clean_line > > clean_csv.append(clean_line) > > So the list has just appended itself to itself, that why python > shows the slightly wierd [...] because its a recursively defined list. That sounds bad - and sure confused me ! > > > print 'clean_csv ',clean_csv > > clean_line = [] > > And now you make clean_line point to a new empty list > So next time round the vcontents ofg the new clean line > will be appended to the old one. > > Go back and initialise your lists as two separate lists and > you will get what you expect. > > > clean_line ['temp1', 'wow a variable'] > > clean_csv ['temp1', 'wow a variable', [...]] > > The original with itself tagged on. > > > clean_line ['temp2'] > > clean_csv ['temp1', 'wow a variable', [...], ['temp2']] > > The above list with the new list added > > Just as expected :-) > > HTH, > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld _______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
