Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python-3.x

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]

like image 547
Haider Yaqoob Avatar asked Jan 28 '26 17:01

Haider Yaqoob


1 Answers

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
like image 56
Demi-Lune Avatar answered Feb 01 '26 08:02

Demi-Lune