Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I create a list of lists where I can index each list individually?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading