[Tutor] Lists in List question

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Jun 24 01:00:51 CEST 2005



On Thu, 23 Jun 2005, Phillip Hart wrote:
> I've been using lists within lists for several functions, but have been
> unable, in loop form, to extract data from them or, in loop for, apply data
> to them.

[cut]

Hi Phillip,

Can you try checking for indentation?  Your code came out indented all on
the left margin, so it's difficult to see if:


> while x<8:
> while y<8:
> print "(",x,", ",y,") is ",results[x][y] ###results[] is a list of lists
> y=y+1
> x=x+1


represents the code block:

######
while x<8:
    while y<8:
        print "(",x,", ",y,") is ",results[x][y]
        y=y+1
        x=x+1
######


or if it represents the code block:

######
while x<8:
    while y<8:
        print "(",x,", ",y,") is ",results[x][y]
        y=y+1
    x=x+1
######

I'll assume for the moment that the second interpretation is what you
have, since the first one makes less sense.  *grin*

Also, you may want to see if you really want to use the "while" loop, or
if a "for" loop is more convenient.  The code as written is handling loop
indicies manually, and there may be a bug in the way you're using it.

Let's take the second code block for the moment:

######
while x<8:
    while y<8:
        print "(",x,", ",y,") is ",results[x][y]
        y=y+1
    x=x+1
######

The 'y' variable does not automatically reset here back to zero at any
given point, so the loop will only run through the first row of the
results.


Try and see if expressing the iteration with a 'for' loop is easier.
Because it has an explicit range(), 'for' often makes it easier to write
the code without having to deal with incrementing index variables by hand.


Best of wishes to you!



More information about the Tutor mailing list