Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find elements in list which occure only one time in list

Tags:

python-3.x

I have written a function which return a list of elements which occur only once in a given list and it is working as expected but this is not what I want is there any built-in function or other method which do same functionalities without iterating:

def unique_items(ls):
    return [item for item in ls if ls.count(item)==1]

print(unique_items([1,1,1,2,3,2,4,5,4]))
like image 759
Vashdev Heerani Avatar asked Jan 01 '26 03:01

Vashdev Heerani


1 Answers

>>> from collections import Counter
>>> a = [1,2,3,4,5,1,2]
>>> c = Counter(a)
>>> c
Counter({1: 2, 2: 2, 3: 1, 4: 1, 5: 1})
>>> [k for k, v in c.items() if v == 1]
[3, 4, 5]
like image 78
Prasad Avatar answered Jan 05 '26 05:01

Prasad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!