[Python] Removing dynamically an element from a list

Discussão em 'Python' iniciado por Stack, Janeiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    My question can looks a bit weird and easy, but I can't find a satisfying answer. I want to iterate on a list, and remove elements from it. The problem happens when there is one element left in the list after a deletion: the loop will not iterate on the last element, just as if the list was empty.

    I am using a for .. in .. like in the following example:

    def test_remove(self):
    """Test to remove all values from a list."""
    test = [4, 5]
    [test.remove(i) for i in test]
    print test


    I am getting the following output:

    [5]


    Does it mean that iterating like I am doing on a list doesn't dynamically resize the list when an element is deleted (same thing is happening using for i in range()) ? Or it is just because i am simply reaching i = len, and so I can't go further ?

    I could always cheat and check when the len is equal to 1 but I would like to understand if there is a more beautiful way to do this.

    Thank you very much.

    Continue reading...

Compartilhe esta Página