Trying to create a 10 by 10 board using lists

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')

For some reason when I try to index the first block and make it the number 1 it makes every list in the outer list number 1 at the beginning. How do I make it so only the first space of the first list becomes number 1? Thank you

Hi jaccobtw. I hope you’re doing well!

That’s a very nice tricky question, let me try to guide you a little bit.

  • Your first part, creating the unit and first list is good, just to simplify a little bit your code you can create a list using arithmetic operations:
list = [" "] * 10
#Prints [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']

Also, if you need to " " be declared as a variable, you can:

unit = " " 
list = [unit] * 10
#Prints [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
  • Then you create your board list, but when you iterate through X in range(10) and append lst, you are referencing your lst within each row, but for creating a 2D list, you want to actually create a new copy of the lst above for each row. So when you update board[0][0] = 1, you change your lst, but that also will change board
    [1][0], board [2][0] and so on…
  • So for creating an actual new copy for each row, you need to create a copy of your previous lst, you can use lst.copy() method or a simple list slicing like this
board = []
for x in range(10):
  row = lst.copy()  # Create a copy of lst using list slicing
  board.append(row)

Or using

board = []
for x in range(10):
  row = llst[:] # Create a copy of lst using list slicing
  board.append(row)

Even better you can use a list comprehension:

board = [lst[:] for row in range(10)]
  • That way you create a new copy for every row and when you update, it will work as an actual board.

The following is the complete code solution:

unit = ' ' lst = [unit] * 10 board = [lst[:] for _ in range(10)] # Use list slicing to create a copy of the list board[0][0] = 1 print(*board, sep='\n') #Note than when we add a new item, it will not modify the previous one board[2][3] = 4 print(*board, sep='\n')

I hope that helps! Let me know if you have any further questions.

Keep going!