Python | List the frequency of elements



Method # 1: Using Counter () + set () + comprehension list
A combination of the above functions can be used to accomplish a task. The Counter function does the grouping, the set function retrieves the individual items as dict keys and checks the list comprehension to appear in the list.

# Python3 demo code
# list of frequency elements
# using Counter () + set () + comprehension list

from collections import Counter

  
# initializing list

test_list = [[ 3 , 5 , 4 ],

[ 6 , 2 , 4 ],

  [ 1 , 3 , 6 ]]

  
# print the original list

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

 
# using Counter () + set () + comprehension list
# list of element frequencies

res = dict (Counter (i for sub in test_list for i in set (sub)))

 
# print result

print ( "The list frequency of elements is:" + str (res))

Output:

 The original list: [[3, 5, 4], [6, 2, 4], [1, 3, 6]] The list frequency of elements is: {1: 1, 2: 1, 3: 2, 4: 2, 5: 1, 6: 2} 

Method # 2: Using Counter () + itertools.chain.from_iterable () + map () + set ( )
The above 4 functions can also be combined to achieve this specific task. The set function retrieves the dictionary keys generated by Counter, the map function performs the task for all sublists, and the from_iterable function performs iterators, which is faster than comprehension of a list.

# Python3 demo code
# list the frequency of items
# using Counter () + itertools.chain.from_iterable () + map () + set ()

from collections import Counter

from itertools import chain

 
# initializing list

test_list = [[ 3 , 5 , 4 ],

[ 6 , 2 , 4 ],

[ 1 , 3 , 6 ]]

 
# print original list

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

  
# using Counter () + itertools.chain.from_iterable () + map () + set ()
# list of element frequencies

res = dict (Counter (chain.from_iterable ( map ( set , test_list))))

 
# print result

print ( " The list frequency of elements is: " + str (res))

Output:

 The original list : [[3, 5, 4], [6, 2, 4], [1, 3, 6]] The list frequency of elements is: {1: 1, 2: 1, 3: 2, 4: 2, 5: 1, 6: 2}