Python Program to Create Frequency Table from List
collections.Counter class, for example: from collections import Counter; freq = Counter(your_list).Examples
How to Think About It
Algorithm
Code
from collections import Counter items = [1, 2, 2, 3, 3, 3] frequency_table = Counter(items) print(dict(frequency_table))
Dry Run
Let's trace the list [1, 2, 2, 3, 3, 3] through the code using Counter.
Initialize list
items = [1, 2, 2, 3, 3, 3]
Create frequency table
frequency_table = Counter(items) counts each item: 1->1, 2->2, 3->3
Print result
print(dict(frequency_table)) outputs {1: 1, 2: 2, 3: 3}
| Item | Count |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
Why This Works
Step 1: Using Counter
The Counter class automatically counts how many times each item appears in the list.
Step 2: Dictionary output
Converting the Counter object to a dictionary shows the frequency table with items as keys and counts as values.
Alternative Approaches
items = [1, 2, 2, 3, 3, 3] frequency_table = {} for item in items: if item in frequency_table: frequency_table[item] += 1 else: frequency_table[item] = 1 print(frequency_table)
items = [1, 2, 2, 3, 3, 3] frequency_table = {item: items.count(item) for item in set(items)} print(frequency_table)
Complexity: O(n) time, O(k) space
Time Complexity
Counting frequencies requires checking each item once, so it takes O(n) time where n is the list length.
Space Complexity
The dictionary stores counts for each unique item, so space is O(k) where k is the number of unique items.
Which Approach is Fastest?
Using Counter is fastest and most readable. Manual counting is similar but more verbose. Dictionary comprehension with count() is slower for large lists.
| Approach | Time | Space | Best For |
|---|---|---|---|
| collections.Counter | O(n) | O(k) | Large lists, simplicity |
| Manual dictionary counting | O(n) | O(k) | No imports, learning purpose |
| Dictionary comprehension with count() | O(n*k) | O(k) | Small lists, concise code |
collections.Counter for a simple and efficient frequency table in Python.