[Tutor] The Python way and two dimensional lists

Phil phillor9 at gmail.com
Mon Nov 22 01:02:34 EST 2021


> Also, using python "2D" lists there is no way to
> access the entire column (in your example) you can
> only access a whole row.

This has always confused me even when I had it working correctly using 
the non Python way. It worked so I accepted it.

I now have this:

num_rows = 9
num_cols = 9

solution = [[0 for i in range(num_cols)] for j in range(num_rows)]

# solution row column

solution[0][0] = {7,3}, {5}, {4,8,6}, {7,8}, {1}, {9,3}, {7,9}, {4,6,3}, 
{2}
solution[0][1] = {1}
solution[0][2] = {2}
solution[0][3] = {3}
solution[0][4] = {4}
solution[0][5] = {5}
solution[0][6] = {6}
solution[0][7] = {7}
solution[0][8] = {8}

So row 0 is {7,3}, {5} etc

and row 1 is {1} followed by 8 zeros

for row in solution:
     print(row[0])

({3, 7}, {5}, {8, 4, 6}, {8, 7}, {1}, {9, 3}, {9, 7}, {3, 4, 6}, {2})
0
0
0
0
0
0
0
0

Why do the sets represent only one position and the eight zeros make up 
the remaining nine positions?

> You can build a copy of a column easily enough with:
>
> col6 = [row[5] for row in solution]
col0 = [row[0] for row in solution]

print('column ', col0)

prints row 0 with 8 extra zeros:

column  [({3, 7}, {5}, {8, 4, 6}, {8, 7}, {1}, {9, 3}, {9, 7}, {3, 4, 
6}, {2}), 0, 0, 0, 0, 0, 0, 0, 0]

It's those extra zeros again.

col0 = [row[6] for row in solution]
print('column ', col0)

prints and this is what I did expect:

column  [{6}, 0, 0, 0, 0, 0, 0, 0, 0]

> But if you change any values you need to regenerate
> the copy so it's not exactly efficient.

Is there a Python way to access any point on the grid with something 
like x = row[6][col7]. This is how I had originally accessed the grid. 
I'm happy to change the entire design so that I have a static grid that 
I can access with a row, col combination. Having to build a column every 
time I want to access it seems like a lot of unnecessary extra effort. 
Should I investigate the array module rather that persisting with lists? 
Arrays make more sense to me.

-- 

Regards,
Phil



More information about the Tutor mailing list