I am trying to modify a dictionary object while iterating over it. But python will raise a RuntimeError
saying that dictionary changed size during iteration
to avoid unexpected behavior(this is expected).
>>> a = {1: 2, 2: 3}
>>> for key in a:
... if key % 2 == 0:
... a.pop(key)
...
3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
But what actually surprised me is that even though the above code block exited with RuntimeError
the dictionary a
got modified.
>>> a
{1: 2}
Why is that?. Is this behavior is documented somewhere?.
Below is my python version and implementation.
>>> import sys, platform
>>> sys.version_info
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
>>> platform.python_implementation()
'CPython'
I believe the reason is because after popping the item, the for
loop fails when trying to move on to the next key value. In other words, the error occurs after removing the key,value pair. See the answers here.