Haider Yaqoob
Haider Yaqoob

Reputation: 1923

Function to remove all the entries of specific duplicate number in the list

How to delete all the entries of specific number from list.

However the way i followed below is just removing one time

newList = [1,2,3,4,5,2,6,7,5,8]
for num in newList:
    if newList.count(num) > 1:
        newList.remove(num)
print(newList)

Result

[1, 3, 4, 2, 6, 7, 5, 8]

Upvotes: 3

Views: 59

Answers (3)

Gugu72
Gugu72

Reputation: 2218

You should try this :

newList = [1,2,3,4,5,2,6,7,5,8]
for num in newList:
    if newList.count(num) > 1:
        for i in newList.count(num):
            newList.remove(num)
print(newList)

Upvotes: 0

Demi-Lune
Demi-Lune

Reputation: 1967

There's 2 issues with your code:

  • you're modifying the list while iterating it. So you miss the next number (the "3" and the 2nd "2")
  • help(list.remove) explicitly says it'll "remove first occurrence of value"

With a couple of print in your code, this becomes obvious:

newList = [1,2,3,4,5,2,6,7,5,8]
for num in newList:
    print (num)
    if newList.count(num) > 1:
        print('   -->removing')
        newList.remove(num)
print(newList)

outputs:

1
2
   -->removing
4
5
   -->removing
6
7
5
8

Upvotes: 1

elomat
elomat

Reputation: 139

Try This:

newList = [1,2,3,4,5,2,6,7,5,8,9,9,9,9]
l = []
for i,v in enumerate(newList):
    if v in l:
        l.pop(l.index(v))
    else:
         l.append(v)

print(l)

Upvotes: 0

Related Questions