13.07 and 13.08 - Why is the length of 'board' list different for the rows and columns?


#1

In 13.7 "Hide...", the random_col function returns a random integer ending with the length of the board:

def random_col(board):
    return randint(0,len(board)-1)

In 13.8 "...And Seek!", the random_col function returns a random integer ending with the length of the board, but it appends a [0] to the board list:

def random_col(board):
    return randint(0, len(board[0]) - 1)

1.) What does this syntax mean?
2.) What is an 'O' being appended to the board list?
3.) Is the CodeAcademy compiler adding this extra syntax? That seems like a great way to confuse new learners.


#2

Hi @psr1234 ,

In this game board, the numbers of rows and columns happen to be the same. But it is possible to have a game with a rectangular board, in which the number of columns differs from the number of rows. We have implemented board as a two dimensional list here ...

for x in range(0, 5):
    board.append(["O"] * 5)

The "outer" dimension is the number of rows, and within each row, we have another dimension, which is the number of columns in that row.

To account for the possibility of a difference between the number of rows and columns, you can write the random_row and random_col functions as follows ...

def random_row(board):
    return randint(0, len(board) - 1)
def random_col(board):
    return randint(0, len(board[0]) - 1)

To pick a row at random, we look at the len of the outer dimension with len(board), which is the number of rows. But to pick a column at random, we use an index, 0, look for the number of columns within the first row, by using len(board[0]).

Allowing for a board in which the number of rows and columns may be different makes the code easier to adapt later on, in case we decide to change the shape of the board. Planning for flexibility is often helpful.


#3

Thanks man! I was having the same problem understanding this. You really cleared it up for me