Count Data in Python with Comprehensions and Generators
Count list items with a dict comprehension and generate squares lazily with a generator expression, printing both results.
Python code
13 linesfrom collections import Counter
data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {item: data.count(item) for item in set(data)}
square_gen = (x * x for x in range(5))
squares = list(square_gen)
if __name__ == "__main__":
print("Manual count:", counts)
print("Counter:", dict(Counter(data)))
print("Squares generator:", squares)
Output
Manual count: {'apple': 3, 'banana': 2, 'cherry': 1}
Counter: {'apple': 3, 'banana': 2, 'cherry': 1}
Squares generator: [0, 1, 4, 9, 16]
How it works
The dict comprehension {item: data.count(item) for item in set(data)} builds a frequency map by iterating over unique items from set(data) and counting each occurrence with .count(). The generator expression (x * x for x in range(5)) creates a lazy sequence of squares, consumed once by list() to produce the final list. Counter from collections offers a more efficient, purpose-built counting method with the same result. Using set(data) avoids redundant counting of duplicates, and the generator saves memory for large ranges by not storing all values at once.
Common mistakes
- Calling `.count()` repeatedly on a large list inside a comprehension can be slow; prefer `Counter` for efficiency.
- Using a list comprehension `[x * x for x in range(5)]` instead of a generator when memory is a concern for large ranges.
- Forgetting that a generator can only be iterated once; converting to a list consumes it.
Variations
- Use `collections.Counter` directly for a succinct and optimized count.
- Use `dict.fromkeys` with manual increments for clearer step-by-step counting.
Real-world use cases
- Counting word frequencies in a text corpus before building a natural language model.
- Generating unique IDs or hash values lazily in a large data stream without loading all into memory.
- Aggregating click counts per user in analytics logs for dashboard reporting.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Cycle an iterable forever in Python easy
Keep learning
Related tutorials and quizzes for this topic.