Count frequencies of all elements in array in Python

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the frequency of all the elements in an array. We can find it in different ways let's explore two of them.

Using dict

  • Initialize the array.

  • Initialize an empty dict.

  • Iterate over the list.

    • If the element is not in dict, then set the value to 1.

    • Else increment the value by 1.

  • Print the element and frequencies by iterating over the dict.

Example

Let's see the code.

# intializing the list
arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
# initializing dict to store frequency of each element
elements_count = {}
# iterating over the elements for frequency
for element in arr:
   # checking whether it is in the dict or not
   if element in elements_count:
      # incerementing the count by 1
      elements_count[element] += 1
   else:
      # setting the count to 1
      elements_count[element] = 1
# printing the elements frequencies
for key, value in elements_count.items():
   print(f"{key}: {value}")

Output

If you run the above program, you will get the following results.

1: 3
2: 4
3: 5

Let's see the second approach using Counter class of the collections module.

Using Counter class

  • Import the collections module.

  • Initialize the array.

  • Pass the list to the Counter class. And store the result in a variable.

  • Print the element and the frequencies by iterating over the result.

Example

See the code below.

# importing the collections module
import collections
# intializing the arr
arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
# getting the elements frequencies using Counter class
elements_count = collections.Counter(arr)
# printing the element and the frequency
for key, value in elements_count.items():
   print(f"{key}: {value}")

Output

If you run the above code, you will get the same output as previous one.

1: 3
2: 4
3: 5

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

raja
Published on 12-Feb-2020 15:42:47
Advertisements