Comprehensions & Generator Expressions
Comprehension — Python-এর সবচেয়ে সুন্দর ফিচার
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).
2. List Comprehensions
Basic form: [expr for item in iterable if condition].
# 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 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.
# 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.
নিয়ম: comprehension ব্যাখ্যা করতে যদি কমেন্ট দরকার হয়, তাহলে সেটিকে সাধারণ লুপে লিখুন।
# 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 (শব্দভাণ্ডার)
| Term | Meaning | বাংলায় |
|---|---|---|
| Comprehension | An expression that builds a collection. | Collection তৈরির expression। |
| Generator expression | Lazy comp; yields on demand. | Lazy comp; চাহিদামতো item দেয়। |
| Lazy evaluation | Compute values only when needed. | প্রয়োজন হলে তবেই মান হিসাব করা। |
| Nested comprehension | A comp inside a comp. | Comprehension-এর ভেতর comprehension। |
| Predicate | The filter condition (if ...). | Filter শর্ত। |
7. Practice Problems
-
Using a list comprehension, build the list of first-10 cubes.List comprehension দিয়ে প্রথম ১০টি সংখ্যার ঘন (cube) তৈরি করুন।
✨ Show Answer (উত্তর দেখুন)
ans1.pycubes = [n ** 3 for n in range(1, 11)] print(cubes) -
From a list of words, keep only those whose length is more than 4.একটি word list থেকে শুধু ৪-এর বেশি length-এর word রাখুন।
✨ Show Answer (উত্তর দেখুন)
ans2.pywords = ["cat", "python", "is", "fun", "mango"] long_ones = [w for w in words if len(w) > 4] print(long_ones) -
Use a dict comprehension to build
{n: n*n}for the numbers 1..5.Dict comprehension দিয়ে{n: n*n}— ১ থেকে ৫ পর্যন্ত — তৈরি করুন।✨ Show Answer (উত্তর দেখুন)
ans3.pysq = {n: n * n for n in range(1, 6)} print(sq) -
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.pytotal = 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"-এর পার্থক্য। -
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.pymat = [[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.
[] list, {k: v ...} dict, {x ...} set, (...) lazy generator। Readability-কে অগ্রাধিকার দিন।