因为如果words被修改的话, for可能无法终止. 例如
>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... if len(w) > 6:
... words.insert(0, w)
...
^CTraceback (most recent call last):
File "<stdin>", line 3, in <module>
KeyboardInterrupt
>>> len(words)
33697
所以建议使用words的拷贝, 例如words[:]就是一种简单的拷贝方法, 不需重新定义一个变量.
>>> words = ['cat', 'window', 'defenestrate']
>>> words[:]
['cat', 'window', 'defenestrate']
>>> for w in words[:]:
... if len(w) > 6:
... words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
[参考]
4.2. for Statements
The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):
>>>
>>> # Measure some strings: ... words = ['cat', 'window', 'defenestrate'] >>> for w in words: ... print(w, len(w)) ... cat 3 window 6 defenestrate 12
If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:
>>>
>>> for w in words[:]: # Loop over a slice copy of the entire list. ... if len(w) > 6: ... words.insert(0, w) ... >>> words ['defenestrate', 'cat', 'window', 'defenestrate']