Sets vs lists loop behaviour if size changes

candide c.candide at laposte.net
Wed Oct 14 17:11:20 EDT 2015


If set size changes during a for loop, a runtime exception is raised:


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
S = {2015}
for z in S:
    S.add(42)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Traceback (most recent call last):
  File "_.py", line 2, in <module>
    for z in S:
RuntimeError: Set changed size during iteration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Surprisingly, if a for loop changes the size of a list it is iterating on, no exception is raised :

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
L = [2015]
for z in L:
    L.append(42)
    print(len(L))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The code above falls into an infinite loop, printing :


2
3
4
5
6
7
8
9
...
198435
198436
198437
^Z

So why lists and sets don't react the same way?



More information about the Python-list mailing list