Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Building a 2D array
#1
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
Reply
#2
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
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
If it's real simple, like your case, you can do a list comprehension:

board = [[' '] * columns for row in range(rows)]
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
Thanks
Reply
#5
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)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020