[Tutor] A list in list problem

Alan Gauld alan.gauld at freenet.co.uk
Mon Aug 21 18:41:59 CEST 2006

>>>> a=b=[]
>>>> a
> []
>>>> b
> []

These are the same list.

>>>> a=[1,2,3]

But here you create a new list and assign it to a.

>>>> a
> [1, 2, 3]
>>>> b
> []

So a points to the new list and b to the original.

> Tinkering some more I think it is the append that did it.

Yes, the append adds the data to the original list.

>>>> a=b=[]
>>>> a
> []
>>>> b
> []
>>>> a.append([1,2,3])
>>>> a
> [[1, 2, 3]]
>>>> b
> [[1, 2, 3]]

Exactly so.

> It appended to the common object and did not create a separate one ?

Yes, the first assignment to 'a' created a new list and broke the
shared reference.

I almost never use the x=y=value style for this reason.
For the minimal amount of typing I prefer either

x = value1
y = value2

or tuple assignment:

x,y = v1,v2

Which for lists is:

x,y = [],[]

ie two separate empty lists.

> I guess var1 = var2 = 0 is generally bad programming style ?

Its fine if you're sure it's what you want, but what it looks like
isn't always what you get... as you discovered  :-)

> get my code more compact using list comprehension etc

Compact code is not always a virtue.
Tuple assignment seems to me a good compromise.
And FWIW I try to limit tuple assignment to 3 values max
just for clarity. Also I try to ensure the variables are linked
in some way - like x,y coordinates, or similar types of variable:
max_len, min_len etc

> PS This is probably an impossible question but I always struggle to 
> find names
> for variables - any hints ?

Write a description of what it is there for - what does it do in the 
Abbreviate that to a couple of key words. That's your name... If you 
a more detailed view find a copy of Code Complete by McConnell, it
has a whole chapter on variable naming issues...
Your variable names looked ok to me FWIW.

Alan G

More information about the Tutor mailing list