Why is list.remove only removing every second item?

后端 未结 6 1603
执念已碎
执念已碎 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:44

    That's because you're modifying the list while iterating over it, iterate over a shallow copy instead:

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

提交回复
热议问题