Introduction
In Python, a list is a collection of items that are ordered and changeable. Sometimes, we need to filter out the unique values from a list. In this challenge, you are required to write a Python function that takes a list as an argument and returns a new list with only the non-unique values.
Filter Unique List Values
Write a Python function called filter_unique(lst) that takes a list as an argument and returns a new list with only the non-unique values. To solve this problem, you can follow these steps:
- Use
collections.Counterto get the count of each value in the list. - Use a list comprehension to create a list containing only the non-unique values.
Your function should satisfy the following requirements:
- The function should take a list as an argument.
- The function should return a new list with only the non-unique values.
- The function should not modify the original list.
- The function should be case-sensitive, meaning that 'a' and 'A' are considered different values.
def filter_unique(lst):
## your code here
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]
Summary
In this challenge, you have learned how to filter out the unique values from a list using Python. You have also learned how to use collections.Counter to count the occurrences of each value in a list and how to use a list comprehension to create a new list with only the non-unique values.