Why is list.remove only removing every second item?

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

    Use a deep copy of mylist

    mylist = [1, 2, 3, 4, 5]
    
    l = [k for k in mylist] # deep copy
    
    for i in range(len(mylist)):
        mylist.remove(l[i])
        print 
    
    print mylist
    

提交回复
热议问题