Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python program to get only the unique which has no duplicate from the list

consider I have a list in python list1=[123,123,724,458,458], I want the output as

list1=[724], the only unique value in list

list1=[100,200,300,300,100];
list1=set(list1);

Gives me

list1=[100,200,300]

But I need

list1=[200]

as output

like image 226
Chris Blesson Avatar asked Oct 20 '25 15:10

Chris Blesson


2 Answers

You can use collections.Counter to count the frequencies of each item in the list, and then select only with frequency 1

from collections import Counter


def get_unique(li):
    #Create the counter to count frequencies
    c = Counter(li)

    #Create a list of items with count 1
    result = [key for key,value in c.items() if value == 1]

    return result

print(get_unique([100,200,300,300,100]))
print(get_unique([123,123,724,458,458]))

The output will be

[200]
[724]
like image 54
Devesh Kumar Singh Avatar answered Oct 23 '25 07:10

Devesh Kumar Singh


You can do it with list comprehension. But you have to keep two objects, your initial list and your list of unique elements. The count method give the number of occurrence of one element in the list.

Here is one way to do:

list1 = [100, 200, 300, 300, 100]

# Convert again to list
list1_unique = list(set(list1))

ans = [unique for unique in list1_unique if list1.count(unique) == 1]
print(ans)
# [200]
like image 30
Alexandre B. Avatar answered Oct 23 '25 06:10

Alexandre B.



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!