In python, what containers properly support mutation during iteration?
For example:
container = [1, 2, 3, 4]
for i in container:
print(i)
if i == 2:
container.append(8)
Outputs 1 2 3 4 8
(lists can be appended during iteration).
However, if I replace .append(8)
with .remove(1)
the output becomes 1 2 4
(i.e., element 3
gets skipped). It seems as if list iteration is over indices not elements, and therefore only subsequent list items (not previous list items) can be safely removed during iteration.
Is there any container in the standard library that does permit elements to be added and removed during iteration, which the behaviour that:
- New elements do get iterated (as for
list.append
), - Removed elements do not subsequently get iterated,
- Whether an element gets iterated over (or not) is never affected by additions/removals of other elements.
The application I have in mind is a registry of event callbacks. When triggered, I would like the callbacks to have the ability to eagerly register or deregister other callbacks for the same event. (If for example I iterated over a temporary copy of the container, I would need to wait for the event to get triggered a second time before changes start taking effect.)