Why is it not safe to modify sequence being iterated on?

前端 未结 3 648
孤城傲影
孤城傲影 2020-11-30 12:35

It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify

3条回答
  •  情书的邮戳
    2020-11-30 12:52

    Without getting too technical:

    If you're iterating through a mutable sequence in Python and the sequence is changed while it's being iterated through, it is not always entirely clear what will happen. If you insert an element in the sequence while iterating through it, what would now reasonably be considered the "next" element in the sequence? What if you delete the next object?

    For this reason, iterating through a mutable sequence while you're changing it leads to unspecified behaviour. Anything might happen, depending on exactly how the list is implemented. :-)

提交回复
热议问题