For loop is skipping some stuff! Python

后端 未结 2 1631
佛祖请我去吃肉
佛祖请我去吃肉 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
    

提交回复
热议问题