Python Program to Find Frequency of Elements in List
collections.Counter(your_list) or by looping through the list and counting each element manually.Examples
How to Think About It
Algorithm
Code
from collections import Counter my_list = [1, 2, 2, 3, 3, 3] frequency = Counter(my_list) print(dict(frequency))
Dry Run
Let's trace the list [1, 2, 2, 3, 3, 3] through the code using Counter.
Input list
my_list = [1, 2, 2, 3, 3, 3]
Count elements
Counter counts each element: 1 once, 2 twice, 3 three times
Convert to dictionary
frequency = {1: 1, 2: 2, 3: 3}
Print result
Output: {1: 1, 2: 2, 3: 3}
| 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: Storing counts
It stores these counts in a dictionary-like object where keys are elements and values are counts.
Step 3: Printing result
Converting to a regular dictionary and printing shows the frequency of each element clearly.
Alternative Approaches
my_list = [1, 2, 2, 3, 3, 3] frequency = {} for item in my_list: if item in frequency: frequency[item] += 1 else: frequency[item] = 1 print(frequency)
my_list = [1, 2, 2, 3, 3, 3] frequency = {item: my_list.count(item) for item in set(my_list)} print(frequency)
Complexity: O(n) time, O(n) space
Time Complexity
Counting frequencies requires checking each element once, so it takes linear time relative to the list size.
Space Complexity
A dictionary stores counts for unique elements, so space depends on the number of unique items.
Which Approach is Fastest?
Using Counter is fastest and most efficient; manual counting is slightly slower but clear; using count() in comprehension is slowest for large lists.
| Approach | Time | Space | Best For |
|---|---|---|---|
| collections.Counter | O(n) | O(n) | Fast and easy for all sizes |
| Manual dictionary counting | O(n) | O(n) | Clear logic without imports |
| Dictionary comprehension with count() | O(n²) | O(n) | Small lists or simple scripts |
collections.Counter for the simplest and fastest way to count frequencies in Python.