[Python] list.remove() skips next element in list

Discussão em 'Python' iniciado por Stack, Julho 12, 2025.

  1. Stack

    Stack Membro Participativo

    I'm programming with lists and have run into a 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 that definitely makes sense. But can someone tell me why it doesn't work? What's behind the veil of Python lists?

    Continue reading...

Compartilhe esta Página