I think I just found a gotcha in Python.
Take a look at the following code:
a = {'a':1, 'b':2, 'c':3}
for i in a.values():
if i == 2:
a['d'] = 4
print(a)
This will result in a RuntimeError of:
Traceback (most recent call last):
File "<string>", line 4, in <module>
RuntimeError: dictionary changed size during iteration
I come from a Java background so this makes sense that you can't actually modify data structures while you are iterating over them.
But this logic falls apart when you see the following code work fine for lists:
a = [1,2,3,4]
for i in iter(a):
if i == 2:
a.extend([5,6,7])
print(a)
The code outputs as expected:
[1, 2, 3, 4, 5, 6, 7]
Why does this work for lists but fail for dictionaries ?
This makes no sense.
I know that dict.values()
, dict.items()
, dict.keys()
all return iterators BUT SO DO LISTS.
This code is using an iterator, right ?
a = [1,2,3,4]
for i in iter(a):
if i == 2:
a.extend([5,6,7])
print(a)
Correct me if I am wrong.
I did check this answer but I failed to get a concrete answer.
Why the special treatment for dictionaries?
Am I missing something very basic here?