Python Program to Count Frequency of Elements
for loop or using collections.Counter like from collections import Counter; freq = Counter(your_list).Examples
How to Think About It
Algorithm
Code
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))
Dry Run
Let's trace the list [1, 2, 2, 3, 3, 3] through the code using Counter.
Import Counter
We import Counter from collections to count elements easily.
Call Counter on list
Counter([1, 2, 2, 3, 3, 3]) creates a dictionary-like object counting each element.
Convert to dict
Convert Counter object to a regular dictionary: {1: 1, 2: 2, 3: 3}.
Print result
Output the frequency dictionary.
| Element | Count |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
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
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]))
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]))
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| collections.Counter | O(n) | O(k) | Quick and easy frequency counting |
| Manual dictionary counting | O(n) | O(k) | Learning and understanding loops |
| defaultdict | O(n) | O(k) | Simplifies manual counting with default values |
collections.Counter for the simplest and fastest way to count frequencies.