Why is list.remove only removing every second item?

后端 未结 6 1605
执念已碎
执念已碎 2021-01-23 04:59

In my Python 2.7.2 IDLE interpreter:

>>> mylist = [1, 2, 3, 4, 5]
>>> for item in mylist:
        mylist.remove(item)

>>> mylist
[2,          


        
6条回答
  •  野的像风
    2021-01-23 05:43

    Problem is that you are altering the list while iterating on it. Use a list comprehension instead:

    mylist = [1, 2, 3, 4, 5]
    mylist = [x for x in mylist if condition(x)]
    

提交回复
热议问题