Python Forum

Full Version: Building a 2D array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to build a game board as part of my Computer Science A-level NEA, I don't know what I am doing wrong can someone please help and fix my code?

space = []

def create_board():
    for i in range (1, 8):
        for j in range (1, 8):
            space[i][j] = " "
        j = j + 1
    i = i + 1

create_board()
Error given:

line 6, in create_board
space[i][j] = " "
IndexError: list index out of range
I generally do this with append:

def create_board(rows, columns):
    board = []
    for row in range(rows):
        board.append([])
        for column in range(columns):
            board[-1].append(' ')
    return board
If it's real simple, like your case, you can do a list comprehension:

board = [[' '] * columns for row in range(rows)]
Thanks
Here are some comments on why your code doesn´t work.
space = []   # You are creating a variable of type list and want to modify this list in a function, BAD IDEA!
 
def create_board():
    for i in range (1, 8):   #  useless blank space between function name and brackets, range(1,8) returns values 1,2,3,4,5,6,7. Is that your intention?
        for j in range (1, 8):
            space[i][j] = " "   # at first start you have an empty list that cannot be accessed with indices like this, there isn´t even a space[0]
        j = j + 1   # what should that be good for? Increasing the loop counter outside the loop? 
                    # the for-loops are already counting from 1 to 7, j is 7 after the loop and you set it to 8 ???
                    # even increasing inside the loop is useless
    i = i + 1    # see above

create_board()  # a function that creates something but doesn´t return it is useless.
Your code refactored in a way it works but not being pythonic.
def create_board(height, width):
    matrix = []
    for y in range(height):
        column = []
        for x in range(width):
            column.append(" ")
        matrix.append(column)
    return matrix
 
space = create_board(8,8)