Friday, August 20, 2021

Python for Beginners: Count the Frequency of Elements in a List

Many times, we need to perform quantitative analysis of data in python. In this article, we will look at some ways to count the frequency of elements in a list. The frequency of an element in a list is defined as the number of times it exists in a list.

Count frequency of elements in a list using for loop

We can count the frequency of elements in a list using a python dictionary. To perform this operation, we will create a dictionary that will contain unique elements from the input list as keys and their count as values. 

To count the frequency of elements in the list, first, we will create an empty dictionary. After that, for each new element, we will count the frequency of the element in the list. After getting the frequency of the element, we will add the element and its frequency as key-value pair to the dictionary.

We will also maintain a list of visited elements to filter out the elements that have been already visited. This can be done as follows.

myList = [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
frequencyDict = dict()
visited = set()
listLength = len(myList)
for i in range(listLength):
    if myList[i] in visited:
        continue
    else:
        count = 0
        element = myList[i]
        visited.add(myList[i])
        for j in range(listLength - i):
            if myList[j+i] == element:
                count += 1
        frequencyDict[element] = count

print("Input list is:", myList)
print("Frequency of elements is:")
print(frequencyDict)

Output:

Input list is: [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
Frequency of elements is:
{1: 2, 2: 2, 3: 3, 4: 1, 46: 1, 7: 1, 5: 1, 6: 1, 10: 1}

In the above example, we are iterating the whole list for each unique element. This makes the algorithm inefficient.  In worst cases, when the list has all unique elements, we will have to process all the elements at least n*(n+1)/2 times where n is the length of the list.

To overcome this shortcoming, we will modify the above algorithm. As an improvement, we will iterate over the list only once. To count the frequency of elements, we will iterate through the list and check for each element if it is already present as a key in the dictionary or not. If the current element is already present as a key in the dictionary, we will increment the count associated with that element by 1. If the current element is not already present as a key in the dictionary, we will add a new item to the dictionary with the current element as key and 1 as its associated value.

We can implement this algorithm as follows.

myList = [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
frequencyDict = dict()
visited = set()
for element in myList:
    if element in visited:
        frequencyDict[element] = frequencyDict[element] + 1
    else:
        frequencyDict[element] = 1
        visited.add(element)

print("Input list is:", myList)
print("Frequency of elements is:")
print(frequencyDict)

Output:

Input list is: [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
Frequency of elements is:
{1: 2, 2: 2, 3: 3, 4: 1, 46: 1, 7: 1, 5: 1, 6: 1, 10: 1}

Improvisation to the above algorithm can be made using python try except blocks.  In this method, we will use the try block to increment the frequency of the elements. Whenever an element is not already present in the dictionary, a KeyError will be raised. This will mean that the element is a unique element and its count hasn’t been added to the dictionary. 

In the except block, we will catch the KeyError and add a new key-value pair to the dictionary with the current element as key and 1 as its associated value. This will be done as follows.

myList = [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
frequencyDict = dict()
for element in myList:
    try:
        frequencyDict[element] = frequencyDict[element] + 1
    except KeyError:
        frequencyDict[element] = 1
print("Input list is:", myList)
print("Frequency of elements is:")
print(frequencyDict)

Output:

Input list is: [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
Frequency of elements is:
{1: 2, 2: 2, 3: 3, 4: 1, 46: 1, 7: 1, 5: 1, 6: 1, 10: 1}

Out of the above two algorithms, The solution which has been implemented using for loop will have almost the same efficiency for each type of input list. Whereas, the solution which uses exception handling will execute much faster for input lists having only a few elements repeated over many times in the list.

Count frequency using the counter() method

We can use the counter() method from the collections module to count the frequency of elements in a list. The counter() method takes an iterable object as an input argument. It returns a Counter object which stores the frequency of all the elements in the form of key-value pairs. We can use the counter() method to calculate the frequency of the elements in the list as follows.

import collections

myList = [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
frequencyDict = collections.Counter(myList)
print("Input list is:", myList)
print("Frequency of elements is:")
print(frequencyDict)

Output:

Input list is: [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
Frequency of elements is:
Counter({3: 3, 1: 2, 2: 2, 4: 1, 46: 1, 7: 1, 5: 1, 6: 1, 10: 1})

Conclusion

In this article, we have discussed different ways to count the frequency of elements in a list. To read more about lists, read this article on list comprehension in python. Stay tuned for more informative articles.

The post Count the Frequency of Elements in a List appeared first on PythonForBeginners.com.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...