linkyndy
linkyndy

Reputation: 17900

Retrieve only non-duplicate elements from a list

What is the best option to retrieve only non-duplicate elements from a Python list? Say I have the following list:

lst = [1, 2, 3, 2, 3, 4]

I would like to retrieve the following:

lst = [1, 4]

(2 and 3 are not unique in that list, so they don't get retrieved)

Upvotes: 0

Views: 143

Answers (2)

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

Use collections.Counter to get counts of items. Combine with a list comprehension to keep only those that have a count of one.

>>> from collections import Counter
>>> lst = [1, 2, 3, 2, 3, 4]
>>> [item for item, count in Counter(lst).items() if count == 1]
[1, 4]

Upvotes: 6

user2555451
user2555451

Reputation:

This is a breeze with a list comprehension:

>>> lst = [1, 2, 3, 2, 3, 4]
>>> [x for x in lst if lst.count(x) == 1]
[1, 4]
>>>

Also, I recommend that you do not name a variable list--it overshadows the built-in.

Upvotes: 5

Related Questions