Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

[1,2,3,2,1]

It should return

[1,2,2,1]

But my program returns

[1,2,1]

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

like image 327
Tori Harris Avatar asked Dec 03 '22 19:12

Tori Harris


1 Answers

If you have a long list, you should put all numbers into a Counter(iterable) - dictionary.

from collections import Counter
data = [1,2,3,2,1]
c = Counter(data)

cleaned = [x for x in data if c[x] > 1]

print(cleaned)

This will count all occurences with one pass of your list (O(n)) and the lookup how often it occurs inside the created dictionary is O(1). Together this is much faster then use a list comprehension like

result = [x for x in data if data.count(x) > 1]

for a list of 100 values it will go through your 100 values 100 times, to count each single one of them wich is O(n^2) - bad thing to have.

Output:

[1,2,2,1]
like image 74
Patrick Artner Avatar answered Dec 15 '22 00:12

Patrick Artner