Skip to content

Python code snippet – How to get frequency of each elements in a list?

# easiest way to count the frequency of all elements in a list
lst = ['Sam', 'Sam', 'Tim', 'Tim', 'Tim', 'r', 'l']

freq = {} # stores the frequency of elements
counting = [freq.update({x: lst.count(x)}) for x in lst]

# output of freq 
{'Sam': 2, 'Tim': 3, 'r': 1, 'l': 1}

#credit: buggyprogrammer.com
#Note: if you print "counting" it will return a list full of None so ignore it. 
See also  Python code snippet - How to make a program on odd and even?
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.