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