0
0
PythonProgramBeginner · 2 min read

Python Program to Count Frequency of Elements

You can count the frequency of elements in a list using a dictionary with for loop or using collections.Counter like from collections import Counter; freq = Counter(your_list).
📋

Examples

Input[1, 2, 2, 3, 3, 3]
Output{1: 1, 2: 2, 3: 3}
Input['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
Output{'apple': 2, 'banana': 3, 'orange': 1}
Input[]
Output{}
🧠

How to Think About It

To count how many times each element appears, start with an empty dictionary. For each element in the list, check if it is already in the dictionary. If yes, increase its count by one; if not, add it with count one. This way, you track the frequency of every element.
📐

Algorithm

1
Create an empty dictionary to store frequencies.
2
For each element in the list, check if it is in the dictionary.
3
If it is, increase its count by one.
4
If it is not, add it to the dictionary with count one.
5
After processing all elements, return the dictionary with frequencies.
💻

Code

python
from collections import Counter

def count_frequency(lst):
    return dict(Counter(lst))

# Example usage
sample_list = [1, 2, 2, 3, 3, 3]
print(count_frequency(sample_list))
Output
{1: 1, 2: 2, 3: 3}
🔍

Dry Run

Let's trace the list [1, 2, 2, 3, 3, 3] through the code using Counter.

1

Import Counter

We import Counter from collections to count elements easily.

2

Call Counter on list

Counter([1, 2, 2, 3, 3, 3]) creates a dictionary-like object counting each element.

3

Convert to dict

Convert Counter object to a regular dictionary: {1: 1, 2: 2, 3: 3}.

4

Print result

Output the frequency dictionary.

ElementCount
11
22
33
💡

Why This Works

Step 1: Using Counter

The Counter class automatically counts how many times each element appears in the list.

Step 2: Dictionary Conversion

Converting the Counter object to a dictionary makes it easy to use and print the frequency counts.

Step 3: Simple and Efficient

This method is concise and efficient, avoiding manual loops and checks.

🔄

Alternative Approaches

Manual dictionary counting
python
def count_frequency_manual(lst):
    freq = {}
    for item in lst:
        if item in freq:
            freq[item] += 1
        else:
            freq[item] = 1
    return freq

print(count_frequency_manual([1, 2, 2, 3, 3, 3]))
This method uses explicit loops and conditions, which is easy to understand but longer than using Counter.
Using defaultdict from collections
python
from collections import defaultdict

def count_frequency_defaultdict(lst):
    freq = defaultdict(int)
    for item in lst:
        freq[item] += 1
    return dict(freq)

print(count_frequency_defaultdict([1, 2, 2, 3, 3, 3]))
defaultdict simplifies dictionary initialization but still requires a loop.

Complexity: O(n) time, O(k) space

Time Complexity

Counting frequencies requires visiting each element once, so time is proportional to the list size n.

Space Complexity

Extra space depends on the number of unique elements k, as each unique element is stored in the dictionary.

Which Approach is Fastest?

Using collections.Counter is optimized in C and usually faster than manual loops or defaultdict.

ApproachTimeSpaceBest For
collections.CounterO(n)O(k)Quick and easy frequency counting
Manual dictionary countingO(n)O(k)Learning and understanding loops
defaultdictO(n)O(k)Simplifies manual counting with default values
💡
Use collections.Counter for the simplest and fastest way to count frequencies.
⚠️
Beginners often forget to initialize counts or check if the element exists before incrementing, causing errors.