This question is not a duplicate of Dictionary changed size during iteration - Code works in Py2 Not in Py3. This question asks why this is not enforced for list
, not how to fix the code.
Python will happily execute
li = [1, 2, 3]
for n in li:
if n % 2 == 0:
li.remove(n)
But if we try with a dict:
a = {1: '', 2: '', 3: ''}
for n in a:
if n % 2 == 0:
a.pop(n)
We get
RuntimeError: dictionary changed size during iteration
Since I assume this is an implementation detail, I'll note that this was tested with CPython 3.7.0 and 3.4.2.