w3resource

Python: Create a list with the non-unique values filtered out


Non-Unique Values in List

Write a Python program to create a list with non-unique values filtered out.

  • Use collections.Counter to get the count of each value in the list.
  • Use a list comprehension to create a list containing only the unique values.

Sample Solution:

Python Code:

# Import the 'Counter' class from the 'collections' module.

from collections import Counter

# Define a function called 'filter_non_unique' that takes a list 'lst' as an argument.
def filter_non_unique(lst):
  # Create a list of items and their corresponding counts using the 'Counter' class.
  # Filter this list to include only items with a count of 1.
  return [item for item, count in Counter(lst).items() if count == 1]

# Example: Filter out non-unique elements from a list.
print(filter_non_unique([1, 2, 2, 3, 4, 4, 5]))

Sample Output:

[1, 3, 5]

Flowchart:

Flowchart: Create a list with the non-unique values filtered out.

For more Practice: Solve these Related Problems:

  • Write a Python program to extract only the non-unique (duplicate) values from a list while preserving their first occurrence order.
  • Write a Python program to filter out non-unique values and return a list that counts how many times each duplicate appears.
  • Write a Python program to create a list of elements that occur more than once in the original list, sorted in descending order.
  • Write a Python program to remove unique values from a list and output only those elements that are repeated.

Python Code Editor:

Previous: Write a Python program to get the difference between two given lists, after applying the provided function to each list element of both.
Next: Write a Python program to create a list with the unique values filtered out.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.