Sets vs lists loop behaviour if size changes

Ian Kelly ian.g.kelly at gmail.com
Wed Oct 14 17:29:32 EDT 2015


On Wed, Oct 14, 2015 at 3:11 PM, candide via Python-list
<python-list at python.org> wrote:
> If set size changes during a for loop, a runtime exception is raised:
>
> [SNIP]
>
> Surprisingly, if a for loop changes the size of a list it is iterating on, no exception is raised :
>
> [SNIP]
>
> So why lists and sets don't react the same way?

Because the behavior of iteration over a set (or dict) that changes
while it's being iterated over is much more difficult to predict.
Though you shouldn't insert or delete items in a list before the
current iteration point, it's generally safe to append items while
iterating.

With a set or dict, *any* items that are added or deleted [1] during
iteration could cause the entire data structure to be rebuilt,
changing the buckets that everything is in and fundamentally altering
the order of iteration. If that happens, all bets are off as to which
items will be iterated over multiple times, which will not be iterated
at all, or how the number of items iterated over will compare to the
actual size of the set or dict.

[1] Merely changing the value of a particular key in a dict is
perfectly safe, however.



More information about the Python-list mailing list