Forum Archive

Recieving error when deleting data from within a list!

amharder

Hello, I am attempting to create sudoku within pythonista, and within the following code I am trying to create the 9x9 space, and place numbers in each square. When I run this, I get the error that whatever x is equal to within the for loop, is not inside of the column in which it has been placed. When I tried to troubleshoot this, I narrowed the issue down to the delete, or del, command used within my code. If I replaced that with a print statement, the code works fine, even though delete has nothing to do with testing to see if x is within its column. My code is below, please help if you can.

import random
board = [[],[],[],[],[],[],[],[],[]]
for column in range(9):
    run = True
    while run:
        x = random.randint(1,9) 
        if x not in board[column]:
            board[column].append(x)
            for y in range(9):
                if y != column: 
                    r = board[column].index(x)
                    if x in board[y]:
                        if r == board[y].index(x):
                            del board[column][r]
        if len(board[column]) == 9:
            run = False
print(board)    

Thank you.

ccc

See #5 in https://www.toptal.com/python/top-10-mistakes-that-python-programmers-make

http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating