Python | Extract least frequency element

Sometimes, while working with data, we can have a problem in which we need to extract element which is occurring least number of times in the list. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using defaultdict() + loop
The combination of above functions can be used to perform this task. In this, we extract each element’s frequency using defaultdict() and extract the minimum frequency element after traversing the defaultdict.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Extract least frequency element
# using defaultdict() + loop
from collections import defaultdict
  
# initialize list 
test_list = [1, 3, 4, 5, 1, 3, 5]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Extract least frequency element
# using defaultdict() + loop
res = defaultdict(int)
for ele in test_list:
   res[ele] += 1 
min_occ = 9999
for ele in res:
    if min_occ > res[ele]:
        min_occ = res[ele]
        tar_ele = ele
  
# printing result
print("The minimum occurring element is : " + str(tar_ele))

chevron_right


Output :



The original list : [1, 3, 4, 5, 1, 3, 5]
The minimum occurring element is : 4

 

Method #2 : Using Counter()
This method is similar to above, the difference is that the frequency is stored using Counter() and then we extract element with least frequency.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Extract least frequency element
# using Counter()
from collections import Counter
  
# initialize list 
test_list = [1, 3, 4, 5, 1, 3, 5]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Extract least frequency element
# using Counter
res = Counter(test_list)
tar_ele = res.most_common()[-1][0]
  
# printing result
print("The minimum occurring element is : " + str(tar_ele))

chevron_right


Output :

The original list : [1, 3, 4, 5, 1, 3, 5]
The minimum occurring element is : 4



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.