Count frequency of items in a list using Python
In this post I am going to show you how we can write a program in Python that can count the frequency of items in a list. First I shall implement it using the dictionary data structure in Python. Then I shall make it shorter (and nicer) using the defaultdict and Counter data structures from the collections module . Here is our code that we will use to run and test the program - if __name__ == "__main__": li = [2, 6, 9, 2, 8, 2, 9, 9, 3, 1, 4, 5, 7, 1, 8, 10, 2, 10, 10, 5] freq = frequency_counter(li) assert freq[1] == 2 assert freq[2] == 4 assert freq[3] == 1 assert freq[11] == 0 Now let's look at the implementation using dictionary. We will iterate over all the items and then check if it exists in the dictionary. If it exists, we shall increase the count. And if it doesn't, then we shall set the count to 1. def frequency_counter(li): freq_dt = dict() for item in li: if item in freq_dt: freq_dt[item] += 1 ...