Python, but not programming, new to here. I program lists and run into an interesting problem.
width = 2 height = 2 # Traverse the board def traverse(x, y): # The four possible directions squares = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)] print squares # Remove impossible squares for square in squares: print "now accessing", square if (square[0] < 1 or square[0] > width or square[1] < 1 or square[1] > height or square == (1, height)): squares.remove(square) print "removed", square print(squares) # Testing traverse traverse(1,1)
The result is the following:
[(0, 1), (2, 1), (1, 0), (1, 2)] now accessing (0, 1) removed (0, 1) now accessing (1, 0) removed (1, 0) [(2, 1), (1, 2)]
It completely skips elements (2,1) and (1,2) - without even checking them! I found the answers here, saying that I should not change the list by looking at it, and yup, it definitely makes sense. Beginners mistake. But can anyone tell me WHY this is not working? What is the veil of Python lists?