3

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

Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
  • 2
    Possible duplicate of [How do I find the duplicates in a list and create another list with them?](https://stackoverflow.com/questions/9835762/how-do-i-find-the-duplicates-in-a-list-and-create-another-list-with-them) – rdas May 21 '19 at 16:01

2 Answers2

2

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]
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
1

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]
Alexandre B.
  • 5,387
  • 2
  • 17
  • 40