How to remove 2nd occurrence of an item in a list using remove() without removing 1st occurrence in Python

前端 未结 3 824
余生分开走
余生分开走 2020-12-04 03:09
a = [9,8,2,3,8,3,5]

How to remove 2nd occurrence of 8 without removing 1st occurrence of 8 using remove().

3条回答
  •  悲&欢浪女
    2020-12-04 03:45

    remove() removes the first item from the list which matches the specified value. To remove the second occurrence, you can use del instead of remove.The code should be simple to understand, I have used count to keep track of the number of occurrences of item and when count becomes 2, the element is deleted.

    a = [9,8,2,3,8,3,5]
    item  = 8
    count = 0
    for i in range(0,len(a)-1):
            if(item == a[i]):
                   count =  count + 1
                   if(count == 2):
                          del a[i]
                          break
    print(a)
    

提交回复
热议问题