Why is list.remove only removing every second item?

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

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

    in this loop : 1st time it will take 0th element (1) as an item and remove it from mylist.so after that mylist will be [2,3,4,5] but the pointer will be in the 1th element of the new mylist ([2,3,4,5]) that is 3. and it will remove 3.so 2 will not be remove from the list.

    thats why after the full operation [2,4] will be left.

    using for loop:-
    >>>for i in range(len(mylist)):
           mylist.remove(mylist[0])
           i-=1
    
    >>>mylist
    []
    

    you can do this using while loop:

    >>>mylist = [1, 2, 3, 4, 5]
    >>>while (len(mylist)>0):
           mylist.remove(mylist[0])
           print mylist
    

提交回复
热议问题