Search code examples
pythonlistrecursionsudokuindices

(Python) TypeError: list indices must be integers, not list


This is some code taken out of a Sudoku solver that I'm working on. I changed a bit of it to shrink it down but the fundamental issue of it is still there. If I were to run this, it would go through the solve function one time but then upon returning to the board[x][y] += 1 part of the add1 function, it returns TypeError: list indices must be integers, not list. I can't find any answers. Can't figure out why a list is being passed instead of just numbers. Please help!

def init_board():
    board = [[],[],[],[],[],[],[],[],[]]
    for i in board:
        for x in range(0,9):
            i.append(0)
    return board

def add1(x, y):
    board[x][y] += 1

def solve(row, column):
    add1(row, column)
    for row in board:
        print(row)
    if True:
        if row == 8 and column == 8:
            return
        if column == 8:
            row += 1
            column = 0
        if column < 8:
            column += 1
        solve(row, column)

board = init_board()

solve(0,0)

Solution

  • Where you put for row in board: you are iterating through board (a list of lists) and setting row to each inner list. Subsequently when you call solve(row, column), you are passing in row, which is now a list.

    If that is not what you intended, change row in for row in board: to a different variable name so it doesn't clash with your existing int variable row.