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 the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient:
>>> for x in a[:]: # make a slice copy of the entire list ... if len(x) > 6: a.insert(0, x) ... >>> a ['defenestrate', 'cat', 'window', 'defenestrate']
为什么只做 for x in a
不安全??
最佳答案
无需太技术性:
如果您在 Python 中迭代一个可变序列,并且在迭代过程中序列发生了变化,那么并不总是完全清楚会发生什么。如果您在迭代时在序列中插入一个元素,那么现在可以合理地将什么视为序列中的“下一个”元素?如果删除下一个对象怎么办?
因此,在更改可变序列时迭代它会导致未指定的行为。任何事情都可能发生,具体取决于列表的具体实现方式。 :-)
关于python - 为什么修改被迭代的序列是不安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3346696/