Python logoPython/
PTC-W0055

Set size changed during iterationPTC-W0055

Critical severityCritical
Bug Risk categoryBug Risk

Sets are represented by a hash table and adding or removing items while iterating over it will alter the iteration order. This will cause a RuntimeError.

If you need to modify the set during iteration, it is recommended to iterate over a [shallow copy]((https://docs.python.org/3/library/copy.html of the dictionary) of the set. A shallow copy creates a new object which stores the reference of the original elements.

For further reading, check

Bad practice

magic_numbers = {0, 1, 1, 2, 3, 5}

for elem in magic_numbers:
    magic_numbers.add(get_next(elem))  # This will raise a `RuntimeError`.
magic_numbers = {0, 1, 1, 2, 3, 5}

for elem in magic_numbers.copy():
    magic_numbers.add(get_next(elem))

References