Python | Extract the lowest frequency element

Learn examples from DataCamp guru:

Method # 1: Using defaultdict () + loop
A combination of the above functions can be used to accomplish this task. In this case, we extract the frequency of each element using defaultdict () and extract the minimum frequency element after passing the defaultdict.

# Python3 demo code
# Extract the lowest frequency element
# using defaultdict () + loop

from collections import defaultdict

 
# initialize the list

test_list = [ 1 , 3 , 4 , 5 , 1 , 3 , 5 ]

 
# print original list

print ( "The original list:" + str (test_list))

 
# Retrieve the lowest 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 & gt; res [ele]:

min_occ = res [ele]

tar_ele = ele

 
# print result

print ( "The minimum occurring element is:" + str (tar_ele))

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 with Counter () and then we retrieve the element with n at the lowest frequency.

# Python3 code to demonstrate how it works
# Extract the lowest frequency element
# using Counter ()

from collections import Counter

 
# initialize the list

test_list = [ 1 , 3 , 4 , 5 , 1 , 3 , 5 ]

 
# print original list

print ( "The original list:" + str (test_list))

  
# Retrieve the lowest frequency element
# using counter

res = Counter (test_list)

tar_ele = res.most_common () [ - 1 ] [ 0 ]

  
# print result

print ( "The minimum occurring element is:" + str (tar_ele))

Output:

 The original list: [1, 3, 4, 5, 1, 3, 5] The minimum occurring element is: 4 
Learn examples from DataCamp guru: