Python, but not programming, newbie here. I'm programming with lists and have 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)
This results in the following output:
[(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 the elements (2,1) and (1,2) -- without even checking them! I found answers here saying I shouldn't be modifying a list while traversing it, and yup, that definitely makes sense. Rookie mistake. But can someone tell me WHY it doesn't work? What's behind the veil of Python lists?