Python | Extract least frequency element

Python | Extract least frequency element

In this tutorial, we'll learn how to extract the element(s) with the least frequency from a list.

Task:

Given a list data_list, find the element(s) that occur the least number of times.

Approach:

  1. Use a dictionary (or collections.Counter) to count the occurrences of each element.
  2. Identify the smallest count value.
  3. Extract all elements that have this count.

Code using a dictionary:

def extract_least_frequent(data_list): """ Extract element(s) with the least frequency from data_list. """ # Count occurrences using a dictionary count = {} for elem in data_list: count[elem] = count.get(elem, 0) + 1 # Find the smallest count value min_count = min(count.values()) # Extract elements that have the smallest count return [key for key, value in count.items() if value == min_count] # Example data_list = [3, 3, 4, 2, 2, 8, 8, 9] print(extract_least_frequent(data_list)) # Output: [4, 9] 

Code using collections.Counter:

from collections import Counter def extract_least_frequent(data_list): """ Extract element(s) with the least frequency from data_list using Counter. """ count = Counter(data_list) min_count = min(count.values()) return [key for key, value in count.items() if value == min_count] # Example data_list = [3, 3, 4, 2, 2, 8, 8, 9] print(extract_least_frequent(data_list)) # Output: [4, 9] 

In the example:

  • The numbers 4 and 9 each appear only once in the list, so they are the least frequent elements.

Additional Notes:

  1. It's possible to have multiple elements with the same minimum frequency. That's why the result is a list that can contain one or more elements.

  2. The function uses the min() function to find the smallest count value in the dictionary.

  3. The collections.Counter class offers a more efficient and concise way to count occurrences.


More Tags

combobox ssid rotativa automator field-description angular6 gstreamer ssms-2012 cockroachdb behaviorsubject

More Programming Guides

Other Guides

More Programming Examples