Suppose we want to represent a $3\times 3$ square of numbers. We already saw how to do that: we can use a nested list. For example, for the square 2 9 4 1 5 6 7 8 3
We can use
square = [[2, 9, 4],
[1, 5, 6],
[7, 8, 3]]
square
Recall that in order to access the second row, we can use:
square[1]
In order to access the 6, we would access the third index in the list that represents the second row:
square[1][2]
(We write is as a square for convenience, but as far as Python is concerned, it's just a list of lists.)
Suppose we want to make sure that there are no repeated numbers in that square (a requirement in the game of Sudoku, for example.) It would be convenient to have a list of all the numbers contained in that square. In other words, it would be convenient to have all data of the form square[i][j], where i = 0..2, j=0..2 in a list. Here is how we can do this:
L = []
for i in range(3):
for j in range(3):
L.append(square[i][j])
print("now appending number at coord.", i, j)
L
Here is how we can now find duplicates:
sorted_L = sorted(L)
for i in range(len(sorted_L)):
if sorted_L[i] != i+1:
print("duplicate found")