I've seen solutions and workaround suggested, but couldn't find an explanation of the choice not to allow changing sets while iterating over them. Can you please help me understand why this is OK
In [1]: l = [1]
In [2]: for i in l:
l.append(2*i)
if len(l)>10:
break
In [3]: l
Out[3]: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
while this is not OK
In [4]: l = {1}
In [5]: for i in l:
l.add(2*i)
if len(l)>10:
break
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-5-b5bdff4a382b> in <module>()
----> 1 for i in l:
2 l.add(2*i)
3 if len(l)>10:
4 break
5
RuntimeError: Set changed size during iteration
What's so bad about changing a set while iterating?
I am aware that the order in set is not defined, so next
might have a hard time. Is this the reason?