Could someone please explain me this


I want to know what happens here

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

why is the row given as len(board) but columns len(board[0])?

def random_col(board):
return randint(0, len(board[0]) - 1) #check this line "board[0])"



indeed it is not an intuitive situation. The fact is that board is not a matrix as we usually understand it. board is only a list. A list can contain anything you want. In the present case, each element of the list is again another list. You can see it when you execute the code

for i in range(5):
print board

it will print out

[[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]]

Then, if you want to know the number of rows in the grid, you need to get the length of the list board, because we don't need to know what is the nature the elements of board

If you want to know the number of columns in the grid, then you are saved because you know that the elements of board are lists. So you need to get the length of one of the element of board. Fortunately, each element of board has the same length, so you can pick up any element you want to get the number of columns (it could also be board[1] which is equal to [1, 1, 1, 1, 1] in my example).


Expanding @thebelgian1's answer, a traditional row-column setup looks like this:

Converting it to a double-dimensional list A list where each element is another list in itself, we get:

board = [ [1, 1, 1],
          [2, 2, 2],
          [3, 3, 3],
          [4, 4, 4] ]

Comparing this to the top-most diagram, we see that 1-1-1 is a row and 1-2-3-4 is a column. This should now be easy to see that the number of columns is the length of one row. Also, the number of rows is the length of one column.


  1. number of columns = length of one row = len(board[0]), since board[0] refers to one (the first) row (We could also take board[1] or board[2], since each row has the same length, but 0 is used for simplicity)
  2. number of rows = length of one column = number of individual lists inside board = len(board)


Oh my goodness! You are right. I was thinking that it was a matrix and missed the simple list concept.
Thank you so much :slight_smile:


Wow ! Now its crystal clear to me !!
My mind thought it as a matrix rather than as a list.
Thanks a lot ! :grin: