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.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 14 views 0 copies

Python code

13 lines
Python 3.9+
from 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

stdout
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

  1. Use `collections.Counter` directly for a succinct and optimized count.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.