Comprehensions & Generator Expressions

Comprehension — Python-এর সবচেয়ে সুন্দর ফিচার

Read: ~25 min Intermediate 5 practice problems Live code runner

1. From Loops to Expressions

A comprehension is a single expression that builds a new list, dict, or set by transforming and (optionally) filtering items from an iterable. It replaces a 4-line for-loop with a one-liner — without losing readability if used thoughtfully. Python offers four flavors: list comprehension, dict comprehension, set comprehension, and generator expression (which is lazy and memory-efficient).

Comprehension একটি মাত্র expression যা একটি iterable থেকে transform ও filter করে নতুন list, dict বা set তৈরি করে। চার লাইনের for-loop এক লাইনে নামিয়ে আনে — readability হারানো ছাড়াই (যদি সতর্ক হয়ে ব্যবহার করেন)। চারটি রূপ: list, dict, set comprehension এবং generator expression (যা lazy এবং মেমরি-সাশ্রয়ী)।

2. List Comprehensions

Basic form: [expr for item in iterable if condition].

list_comp.py
# Squares 1..10
squares = [n * n for n in range(1, 11)]
print(squares)

# With filter
even_squares = [n * n for n in range(1, 11) if n % 2 == 0]
print(even_squares)

# Transform strings
words = ["python", "is", "fun"]
caps = [w.upper() for w in words]
print(caps)

# Flatten a 2-D list
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [x for row in matrix for x in row]
print(flat)

3. Dict and Set Comprehensions

dict_set.py
# Dict comprehension — char → count
s = "programming"
count = {c: s.count(c) for c in set(s)}
print(count)

# Set comprehension — unique lengths
words = ["dhaka", "cox", "sylhet", "cse", "mit"]
lengths = {len(w) for w in words}
print(lengths)

# Build a lookup table
menu = {"rice": 70, "dal": 110, "fish": 220}
pricey = {k: v for k, v in menu.items() if v >= 100}
print(pricey)

4. Generator Expressions — Lazy and Memory-Efficient

A generator expression looks like a list comp but uses () instead of []. It does not build the full list in memory — it yields one item at a time. This lets you process huge sequences without running out of RAM.

genexp.py
# Sum of squares — a generator passes items to sum()
total = sum(n * n for n in range(1, 1001))
print(total)

# Memory: list comp builds 1M items; genexp keeps only one at a time
import sys
print(sys.getsizeof([n for n in range(10000)]))   # big
print(sys.getsizeof((n for n in range(10000))))   # tiny

# any() and all() short-circuit through a genexp
words = ["hello", "world", "", "python"]
print(any(len(w) == 0 for w in words))
print(all(len(w) > 0 for w in words))

5. Readability Rules

Comprehensions are a scalpel, not a hammer. If your comprehension needs more than one for and one if, or runs longer than one readable line, use an ordinary loop. Clever ≠ readable.

Rule of thumb: if you need to add a comment to explain the comprehension, rewrite it as a loop.

নিয়ম: comprehension ব্যাখ্যা করতে যদি কমেন্ট দরকার হয়, তাহলে সেটিকে সাধারণ লুপে লিখুন।
readable.py
# Clean — one for, one if
positives = [x for x in [-2, -1, 0, 1, 2] if x > 0]
print(positives)

# Getting dense — still okay
pairs = [(i, j) for i in range(3) for j in range(3) if i != j]
print(pairs[:4])

# Too dense — rewrite as loop
# result = [complex_fn(a, b, c) for a in xs for b in ys for c in zs if cond(a,b) and check(c)]

6. Vocabulary (শব্দভাণ্ডার)

TermMeaningবাংলায়
ComprehensionAn expression that builds a collection.Collection তৈরির expression।
Generator expressionLazy comp; yields on demand.Lazy comp; চাহিদামতো item দেয়।
Lazy evaluationCompute values only when needed.প্রয়োজন হলে তবেই মান হিসাব করা।
Nested comprehensionA comp inside a comp.Comprehension-এর ভেতর comprehension।
PredicateThe filter condition (if ...).Filter শর্ত।

7. Practice Problems

  1. Using a list comprehension, build the list of first-10 cubes.
    List comprehension দিয়ে প্রথম ১০টি সংখ্যার ঘন (cube) তৈরি করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans1.py
    cubes = [n ** 3 for n in range(1, 11)]
    print(cubes)
  2. From a list of words, keep only those whose length is more than 4.
    একটি word list থেকে শুধু ৪-এর বেশি length-এর word রাখুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans2.py
    words = ["cat", "python", "is", "fun", "mango"]
    long_ones = [w for w in words if len(w) > 4]
    print(long_ones)
  3. Use a dict comprehension to build {n: n*n} for the numbers 1..5.
    Dict comprehension দিয়ে {n: n*n} — ১ থেকে ৫ পর্যন্ত — তৈরি করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans3.py
    sq = {n: n * n for n in range(1, 6)}
    print(sq)
  4. Using a generator expression, compute the sum of squares from 1 to 100 and explain why this is more memory-efficient than a list comp.
    Generator expression দিয়ে ১ থেকে ১০০ পর্যন্ত square-এর যোগফল বের করুন। এটি কেন list comp-এর চেয়ে মেমরি-সাশ্রয়ী?
    ✨ Show Answer (উত্তর দেখুন)
    ans4.py
    total = sum(n * n for n in range(1, 101))
    print(total)

    Why: A list comprehension builds the full list of 100 squares in memory first, then calls sum(). A generator expression yields one square at a time — only one value lives in memory at any moment. For small N the difference is invisible; for millions of items, it is the difference between running and crashing.

    List comp আগে সব ১০০টি square মেমরিতে তৈরি করে, পরে sum() ডাকে। Generator expression এক এক করে মান তৈরি করে — যেকোনো মুহূর্তে মেমরিতে মাত্র একটি মান থাকে। লক্ষ লক্ষ item হলে এটিই "চলবে vs crash"-এর পার্থক্য।

  5. Flatten [[1,2,3],[4,5],[6,7,8,9]] into a single list using a comprehension.
    উপরের 2-D list-কে comprehension দিয়ে 1-D করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans5.py
    mat = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
    flat = [x for row in mat for x in row]
    print(flat)

Summary — Module 17

Comprehensions turn transform-and-filter loops into expressive one-liners. Use the right flavor: [] for lists, {k: v for ...} for dicts, {x for ...} for sets, and (...) for lazy generator expressions. Prefer readability — if you need more than one for and one if, a regular loop is often clearer.

Comprehension transform-filter লুপগুলোকে এক-লাইনের expression-এ পরিণত করে। সঠিক রূপ বেছে নিন — [] list, {k: v ...} dict, {x ...} set, (...) lazy generator। Readability-কে অগ্রাধিকার দিন।

Next Module → Iterators, Generators & yield।