Understanding How Python Generates Lists
· 5 min read
While working on a Python project, I encountered a bug related to list initialization that caused me some frustration. Here’s a breakdown of how I discovered the issue and solved it.
The Program
Here’s a simple program I was working on to check if a 9x9 Sudoku board is valid:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = [0] * 9
columns = [0] * 9
boxes = [[0] * 3] * 3
for i in range(9):
for j in range(9):
if board[i][j] == '.': continue
val = int(board[i][j]) - 1
if ((1 << val) & rows[i]):
return False
if ((1 << val) & columns[j]):
return False
if ((1 << val) & boxes[i//3][j//3]):
return False
rows[i] |= (1 << val)
columns[j] |= (1 << val)
boxes[i//3][j//3] |= (1 << val)
return True
In this program, I use bitwise operations to track the values in each row, column, and 3x3 box on the Sudoku board.
I initialize the rows and columns as 1D lists of bitmasks (using the [0] * 9
method), and the boxes
variable is intended to store bitmasks for each 3x3 square in the board.
However, I ran into an unexpected problem.