Python iterator when underlying object changes

前端 未结 3 1364
-上瘾入骨i
-上瘾入骨i 2021-01-20 11:37

I would like to know what\'s the general behaviour of an iterator if the underlaying object changes during the iteration.

Using a simple mutable list, it seems obvi

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-20 12:02

    There are three typical behaviours of changing an object while iterating over it:

    • the new data will be returned
    • the new data will be ignored
    • old data will be skipped

    In other words: the actual behaviour is undefined.

    Changing objects while iterating over them was such a common problem that in Python 3 the types set and dict (and possibly others) were changed to immediately raise an error if additions or removals were detected during iteration.

提交回复
热议问题