list.count() says one item in list when there are two

  • A+

I have written some code in python to delete unique numbers from a list so given the input:


It should return


But my program returns


My code is:

for i in data:     if data.count(i) == 1:         data.pop(i) 

I found the error occurs at the if data.count(i) == 1:. It says data.count(2) == 1 when clearly there are 2 occurrences of the number 2 in the list. I do not understand why this is giving the wrong answer


Try appending to a new list rather than changing your old one:

res = [] data = [1,2,3,2,1]  for i in data:     if data.count(i) > 1:         res.append(i) 

It's bad practice to change list size during iteration, and pop will do that. This returns res = [1, 2, 2, 1]


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: