I’m trying to create a list that contains 10 lists each with ten empty "space" strings making a ten by ten matrix. The problem is that when I index to add a number to the first position, it adds a 1 to the beginning of each list in the outer list. How do I make it so when I index it only adds a 1 to the first position of the entire matrix (the first spot of the first list in the outer list)?
unit = ' '
lst = []
for y in range(10):
lst.append(unit)
board = []
for x in range(10):
board.append(lst)
board[0][0] = 1
print(*board, sep = '\n')
This code makes is so a 1 appears at the beginning of each list in the outer list. But I want only a 1 at the beginning of the first list.
>Solution :
You could just use list on a string which makes a list of each character in the string.
unit = " " * 10
board = [list(unit) for _ in range(10)]
board[0][0] = 1
Result
[
[1, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
]