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

前端 未结 3 647
孤城傲影
孤城傲影 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:43

    When you modify a collection that you are iterating over the iterator can behave unexpectedly, for example missing out items or returning the same item twice.

    This code loops indefinitely when I run it:

    >>> a = [ 'foo', 'bar', 'baz' ]
    >>> for x in a:
    ...    if x == 'bar': a.insert(0, 'oops')
    

    This is because the iterator uses the index to keep track of where it is in the list. Adding an item at the beginning of the list results in the item 'bar' being returned again instead of the iterator advancing to the next item.

提交回复
热议问题