[Tutor] A list in list problem

Alan Gauld alan.gauld at freenet.co.uk
Mon Aug 21 14:40:55 CEST 2006


> 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.

>            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.

>            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 



More information about the Tutor mailing list