Vashdev Heerani
Vashdev Heerani

Reputation: 679

Find elements in list which occure only one time in list

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]))

Upvotes: 3

Views: 1877

Answers (3)

Ralf
Ralf

Reputation: 16485

Comparing some options mentioned here:

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

def func_2(ls):
    c = collections.Counter(ls)
    return [
        k
        for k, v in c.items()
        if v == 1]

Comparisson code:

import timeit
a_1 = [1,1,1,2,3,2,4,5,4]
a_2 = [1,1,1,2,3,2,4,5,4] * 100

for f in [func_1, func_2]:
    print(f.__name__)
    print(
        'short list',
        timeit.timeit(
            'f(a)',
            'from __main__ import {} as f, a_1 as a'.format(f.__name__),
            number=100))
    print(
        'long list ',
        timeit.timeit(
            'f(a)',
            'from __main__ import {} as f, a_2 as a'.format(f.__name__),
            number=100))

Results:

func_1
short list 0.00014933500006009126
long list  0.5417057829999976
func_2
short list 0.0005539439998756279
long list  0.0029211379996922915

So far, func_2 is faster for large inputs and func_1 is slightly faster for very short inputs.

Upvotes: 1

Djaouad
Djaouad

Reputation: 22766

If you don't want to use an explicit loop, you can use filter:

def unique_items(ls):
    return list(filter(lambda s : ls.count(s) == 1, ls))

print(unique_items([1,1,1,2,3,2,4,5,4]))

Output:

[3, 5]

Upvotes: 2

Prasad
Prasad

Reputation: 6034

>>> 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]

Upvotes: 2

Related Questions