Problem: Given a list, find how many times a number is present in the list (i.e frequency of elements in the list) in Python.

Example:

Input:  [13, 4, 4]
Output: [(13, 1), (4, 2)]

To count the frequency of each element in the list, we create an empty dictionary and iterate through the items of the list.

When we encounter an item for the first time (it does not exist in the dictionary), we start counting them by storing them in the dictionary as dictionary[item] = 1 otherwise, we simply increment its value by 1.

l = [6, 4, 5, 6, 1, 3, 7, 9, 5, 10, 6]

#create empty dictionary to store count
count = {}

for x in l:
    '''
    if x exist in the dictionary then
    increment its value by 1, otherwise
    initilize its value with 1.
    '''
    if x in count:
        count[x] += 1
    else:
        count[x] = 1
        
#output the dictionary
print(count)

Output:

{1: 1, 3: 1, 4: 1, 5: 2, 6: 3, 7: 1, 9: 1, 10: 1}

Leave a Reply