HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

Filter unique list values

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
filteruniquepythonlistvalues

Problem

Using collections.Counter, you can get the count of each value in the list. Then, you can use a list comprehension to filter out the unique values from a list.
Similarly, you can create a list with the non-unique values filtered out. All you need to do is to change the condition in the list comprehension.

Solution

from collections import Counter

def filter_unique(lst):
  return [item for item, count in Counter(lst).items() if count > 1]

filter_unique([1, 2, 2, 3, 4, 4, 5]) # [2, 4]

Code Snippets

from collections import Counter

def filter_unique(lst):
  return [item for item, count in Counter(lst).items() if count > 1]

filter_unique([1, 2, 2, 3, 4, 4, 5]) # [2, 4]
from collections import Counter

def filter_non_unique(lst):
  return [item for item, count in Counter(lst).items() if count == 1]

filter_non_unique([1, 2, 2, 3, 4, 4, 5]) # [1, 3, 5]

Context

From 30-seconds-of-code: filter-unique

Revisions (0)

No revisions yet.