For loop is skipping some stuff! Python

人盡茶涼 提交于 2019-12-02 08:12:13

When you run input.remove(possible_word) you're changing the size of the list which you happen to be iterating over, which leads to peculiar results. In general, don't mutate anything that you're iterating over.

More concise example:

>>> lst = ['a', 'b', 'c']
>>> for el in lst:
    print el
    lst.remove(el)

a
c

Jon Clements is right. You generally don't want to do something like this. However I'll assume you have a specific need for it.

The answer is simple. Change the line

for possible_word in input:

to this line

for possible_word in input[:]:

This will make a copy of the list for you to iterate over. That way when you remove an item it won't effect your loop.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!