你说的是第二个例子吧。
这里说的很清楚啊,在循环内需要对序列进行修改操作时,建议先拷贝一份副本,这是因为在循环过程中序列已经不是原来的序列了可能会导致重复选中某一元素。
就拿你截图中这个例子来说吧。
words=['cat','window','defenestrate']
for w in words:
if len(w)>6:
words.insert(0,w)
若不用副本,
第一次循环的时候,w=words[0]='cat',len(w)=3<6,不执行insert操作,words不变,words=['cat','window','defenestrate'];
第二次循环的时候,w=words[1]='window',len(w)=6,不执行insert操作,words不变,words=['cat','window','defenestrate'];
第三次循环的时候,w=words[2]='defenestrate',len(w)=12>6,执行insert操作,words改变,words=['defenestrate','cat','window','defenestrate'];
第四次循环的时候,w=words[3]='defenestrate',len(w)=12>6,执行insert操作,words改变,words=['defenestrate','defenestrate','cat','window','defenestrate'];
之后每次循环,words长度都会增加,w选中的永远都是'defenestrate'。因此进入死循环。
所以,在循环中若需要对序列进行操作时,一般建议用切片拷贝副本作为循环条件。