[Python] Modify list and dictionary during iteration, why does it fail on dict?

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

  1. Stack

    Stack Membro Participativo

    Let's consider this code which iterates over a list while removing an item each iteration:

    x = list(range(5))

    for i in x:
    print(i)
    x.pop()


    It will print 0, 1, 2. Only the first three elements are printed since the last two elements in the list were removed by the first two iterations.

    But if you try something similar on a dict:

    y = {i: i for i in range(5)}

    for i in y:
    print(i)
    y.pop(i)


    It will print 0, then raise RuntimeError: dictionary changed size during iteration, because we are removing a key from the dictionary while iterating over it.

    Of course, modifying a list during iteration is bad. But why is a RuntimeError not raised as in the case of dictionary? Is there any good reason for this behaviour?

    Continue reading...

Compartilhe esta Página