In this article, we are going to learn how to find the frequency of elements in a list. We can solve the problem in different ways. Let's see two of them.
Follow the below steps to write the code.
- Initialize the list with elements and an empty dictionary.
- 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.
- Print the dictionary.
Example
Let's see the code.
# initializing the list
random_list = ['A', 'A', 'B', 'C', 'B', 'D', 'D', 'A', 'B']
frequency = {}
# iterating over the list
for item in random_list:
# checking the element in dictionary
if item in frequency:
# incrementing the counr
frequency[item] += 1
else:
# initializing the count
frequency[item] = 1
# printing the frequency
print(frequency)If you run the above code, then you will get the following result.
Output
{'A': 3, 'B': 3, 'C': 1, 'D': 2}
Follow the below steps to the problem in another way. We are going to use a module method to find the frequency of elements.
- Import the collections module.
- Initialize the list with elements.
- Get the frequency of elements using Counter from collections module.
- Convert the result to dictionary using dict and print the frequency.
Example
Let's see the code.
# importing the module
import collections
# initializing the list
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))
{'A': 3, 'B': 3, 'C': 1, 'D': 2}If you run the above code, then you will get the following result.
Output
{'A': 3, 'B': 3, 'C': 1, 'D': 2}
Conclusion
If you have any queries in the article, mention them in the comment section.