Skip to content

Python count frequency in list

  • by

You can solve the Python count frequency in the list in different ways. The simplest way would be to iterate over the list and use each distinct element of the list as a key of the dictionary and store the corresponding count of that key as values.

Python count frequency in the list

Simple example code.

Method 1:

Initialize the list with elements and an empty dictionary and Iterate over the list of elements.

  • Check whether the element is present in the dictionary or not.
  • If the element is already present in the dictionary, then increase its count.
  • If the element is not present in the dictionary, then initialize its count with 1.
# initializing the list
random_list = ['A', 'A', 'B', 'C', 'B', 'D', 'D', 'A', 'B']
res = {}

# iterating over the list
for item in random_list:
    # checking the element in dictionary
    if item in res:
        # incrementing the counr
        res[item] += 1
    else:
        # initializing the count
        res[item] = 1
        
print(res)

Output:

Python count frequency in the list

Or use a module method to find the frequency of elements.

import collections


random_list = ['A', 'A', 'B', 'C', 'B', 'D', 'D', 'A', 'B']

# using Counter to find frequency of elements
frequency = collections.Counter(random_list)

# printing the frequency
print(dict(frequency))

An alternative approach can be to use the list.count() method. 

def cf(my_list):
    freq = {}
    for items in my_list:
        freq[items] = my_list.count(items)

    for key, value in freq.items():
        print("% d : % d" % (key, value))

# Driver function
if __name__ == "__main__":
    my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
    cf(my_list)

Output:

 1 :  5
 5 :  2
 3 :  3
 4 :  3
 2 :  4

Do comment if you have any doubts on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published.

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