3/19


#1

board = []
for i in range(5):
board.append([“O”] * 5)

This is the code I used to make a 5 x5 grid containing zeros. From what I understand what this is creating is a list of 5 elements with each element containing a list of 5 'O’s. But why is it in the form of a grid? It can also present as a list horizontally containing 5 elements horizontally (with each elements of another list 5 elements) as shown? Please correct my misunderstanding

[ [‘O’, ‘O’, ‘O’, ‘O’, ‘O’], [‘O’, ‘O’, ‘O’, ‘O’, ‘O’], [‘O’, ‘O’, ‘O’, ‘O’, ‘O’], [‘O’, ‘O’, ‘O’, ‘O’, ‘O’], [‘O’, ‘O’, ‘O’, ‘O’, ‘O’] ]


#2

It only appears as a grid when presented that way. Lists are linear and without demarcation present that way.

>>> def board_template(r, c): return [['O'] * c for x in range(r)]

>>> board_template(5,5)
[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]
>>> 

And now,

>>> print '\n'.join([" ".join(row) for row in board_template(5,5)])
O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
>>> 

#3

So in your first code, what you have made is just a list containing more lists presented in linear form.

In your second code, by using the ‘join’ feature to remove the quotation marks, you turned it into a grid presentation?


#4

Nothing of the sort. .join converts a list to a string. It matters that the list is of string elements to begin with.


#6

Thank you so much for your response.

Would it be correct to say that the grid is a list of 5 elements, with each element being a string?

If so, why does it present as a grid and not present linearly (horizontally) as:
[0 0 0 0 0, 0 0 0 0 0, 0 0 0 0 0, 0 0 0 0 0, 0 0 0 0 0]


#7

The structure is a list of lists.

[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]

The inner join creates strings from each inner list,

'O O O O O`

The outer join creates one large string with newline characters to insert linebreaks.

'O O O O O
O O O O O
O O O O O
O O O O O
O O O O O'

#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.