-4

Making a treasure hunt game and for the board, I would like numbers along the top and side for coordinates of a grid, the top line will be the numbers 0-8 in a list. Here's my code:

board=[]
board.append([])
for i in range(9):
    i2=str(i)
    board[i].append(i2)

Although when i run it I get the error:

board[i].append(i2)

IndexError: list index out of range

  • Here is a list with the first element as a space, and then the first nine digits `[' ', *map(str, range(9))]` Should work on 3.5+. Or for just the numbers `[str(i) for i in range(9)]` – Patrick Haugh Jan 13 '17 at 21:25
  • @MooingRawr actually it'd go out of range at `i=1` since indexing starts at 0, @LMSystem815 if you append a single sublist then you only have a single sublist, what are you expecting? – Tadhg McDonald-Jensen Jan 13 '17 at 21:26

2 Answers2

1

Use list comprehension,

board = [[str(i) for i in range(9)]]
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0

When you try to input into board[1] (when the loop goes for the second time) python crashes since that sub-list doesn't exist replace board[i] with board[0]:

board=[]
board.append([])
for i in range(9):
    i2=str(i)
    board[0].append(i2)