For loop is skipping some stuff! Python

后端 未结 2 1608
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-26 06:53

I\'m trying to run this code so that it runs a function for all elements of a list. For illustrative purposes here, basically it should print:

\'----------Possi         


        
相关标签:
2条回答
  • 2021-01-26 07:40

    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
    
    0 讨论(0)
  • 2021-01-26 07:52

    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.

    0 讨论(0)
提交回复
热议问题