Strings & Data Structures
Comprehensions
Complete lesson for Comprehensions using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Comprehensions
Section: Strings & Data Structures. Python comprehensions — list, set, dict, and generator expressions for clear data transforms.
What is a comprehension?
- A **comprehension** builds a collection from an iterable in one expression: transform + optional filter.
- Forms: list
[...], set{...}, dict{k: v ...}, and generator(...)(lazy). - **Real-life:** a packing list — take each item, keep only what fits, pack into a box.
| Form | Result | Example idea |
|---|---|---|
| List | Ordered sequence | Squares of numbers |
| Set | Unique values | Unique lengths of words |
| Dict | Key-value map | Word → length |
| Generator | Lazy iterator | Stream large ranges |
nums = [1, 2, 3, 4, 5]
squares = [n * n for n in nums]
print(squares) List comprehension with filter
- Syntax:
[expr for item in iterable if condition]. - Read left-to-right: loop, optional filter, then expression.
- Prefer comprehensions for simple map/filter; keep complex logic as a loop or helper function.
nums = range(10)
evens = [n for n in nums if n % 2 == 0]
labels = ["even" if n % 2 == 0 else "odd" for n in range(5)]
print(evens)
print(labels) Set comprehension
{expr for item in iterable}builds a set — duplicates collapse.- Great for unique normalized values (lowercased emails, stripped tags).
words = ["Apple", "banana", "APPLE", "Banana", "cherry"]
unique = {w.lower() for w in words}
print(unique) Dict comprehension
{key_expr: value_expr for item in iterable}builds a mapping.- Later duplicate keys overwrite earlier ones.
- Common: invert maps, index records, compute derived fields.
names = ["Ada", "Bob", "Cia"]
lengths = {name: len(name) for name in names}
grades = {"Ada": 90, "Bob": 75}
passed = {k: v for k, v in grades.items() if v >= 80}
print(lengths)
print(passed) Generator expressions
(expr for item in iterable)is lazy — computes values on demand.- Use with
sum,any,all,maxto avoid building huge lists. - A generator expression can be consumed only once.
gen = (n * n for n in range(5))
print(sum(gen))
print(sum(n * n for n in range(5)))
print(any(n > 3 for n in range(5))) Nested loops in comprehensions
- Multiple
forclauses run like nested loops, left to right = outer to inner. - Example: flatten a matrix or build coordinate pairs.
- If nesting hurts readability, use ordinary nested
forloops.
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [x for row in matrix for x in row]
pairs = [(i, j) for i in range(2) for j in range(3)]
print(flat)
print(pairs) Comprehension vs map/filter
- List comps are usually clearer than
map+lambdafor simple transforms. filter+ list can be replaced withifin a comprehension.- Keep
map/filterwhen composing callables or working with iterators functionally.
nums = [1, 2, 3, 4, 5]
a = [n * 2 for n in nums if n % 2 == 1]
b = list(map(lambda n: n * 2, filter(lambda n: n % 2 == 1, nums)))
print(a)
print(b) Unpacking inside comprehensions
- You can unpack tuples in the
fortarget:for k, v in items. - Enumerate pairs cleanly:
{i: v for i, v in enumerate(seq)}.
pairs = [("a", 1), ("b", 2), ("c", 3)]
doubled = {k: v * 2 for k, v in pairs}
indexed = {i: ch for i, ch in enumerate("hi")}
print(doubled)
print(indexed) Advanced — Comprehensions
Nested list comprehensions (matrices)
- Transpose pattern:
[[row[i] for row in matrix] for i in range(cols)]. - Inner comprehension runs fully for each outer iteration.
- Watch variable scope: in Python 3, comprehension iteration variables do not leak to the enclosing scope.
matrix = [[1, 2, 3], [4, 5, 6]]
transpose = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transpose)
print([[i * j for j in range(1, 4)] for i in range(1, 4)]) Walrus operator in comprehensions
- Python 3.8+
:=can capture a computed value used in both filter and expression. - Use sparingly — clarity beats clever one-liners.
- Avoid side effects inside comprehensions (I/O, mutating outer state).
values = ["10", "bad", "25", "3"]
parsed = [n for s in values if (n := s.isdigit() and int(s)) and n > 5]
# clearer approach:
out = []
for s in values:
if s.isdigit():
n = int(s)
if n > 5:
out.append(n)
print(parsed)
print(out) When NOT to use a comprehension
- Multi-step logic, early
break/continueneeds, or heavy branching → use a loop. - Building and mutating the same structure mid-pass is clearer as statements.
- Side-effect-only loops (
for x in xs: print(x)) should stay as loops, not list comps.
# Prefer loop when accumulating with conditions
nums = [4, -1, 7, 0, 2]
pos = []
seen_zero = False
for n in nums:
if n == 0:
seen_zero = True
break
if n > 0:
pos.append(n)
print(pos, seen_zero) Performance and memory notes
- List comps allocate the full result; generator expressions stream.
- For huge data, prefer generators / itertools over giant lists.
- Microbenchmarks aside, choose the form that reads best for the team.
import sys
lst = [n for n in range(1000)]
gen = (n for n in range(1000))
print(sys.getsizeof(lst), sys.getsizeof(gen))
print(sum(n for n in range(1000) if n % 2 == 0)) Tricky Interview Points
Q1) What is a list comprehension?
Answer A concise expression that builds a list by evaluating an expression for each item in an iterable, optionally filtered by a condition.
Q2) List comprehension vs generator expression?
Answer List comps eagerly build a list in memory. Generator expressions are lazy iterators with parentheses and lower memory use.
Q3) How do you write a dict comprehension?
Answer {key_expr: value_expr for item in iterable if condition} — braces with a key:value pair.
Q4) Do comprehension variables leak in Python 3?
Answer No. The iteration variable is local to the comprehension and does not overwrite same-named outer variables.
Q5) How does nested for order work in a comprehension?
Answer Left-to-right matches nested loops: the leftmost for is the outer loop.
Q6) Can you have multiple if clauses?
Answer Yes — each if filters after its preceding for. You can also use a single if with and.
Q7) When are comprehensions a bad idea?
Answer When logic is complex, needs break/return mid-stream, or is side-effect heavy. Prefer plain loops for clarity.
Q8) Set comprehension vs list then set()?
Answer Set comps build uniqueness directly. Both work; comps avoid an intermediate full list if you only need the set.
Q9) How to flatten a 2D list with a comprehension?
Answer [x for row in matrix for x in row] — outer rows first, then elements.
Q10) Is map faster than a list comprehension?
Answer Often similar; readability usually favors comprehensions for simple transforms. Measure if it truly matters.
Q11) What does {x for x in xs} produce?
Answer A set of unique values from xs (set comprehension), not a dict — dict comps need key: value.
Simple Programs
Squares and filtered squares
nums = list(range(1, 11))
print([n * n for n in nums])
print([n * n for n in nums if n % 2 == 0]) Word length dictionary
sentence = "comprehensions make transforms concise"
d = {w: len(w) for w in sentence.split()}
print(d)
print({w for w in sentence.split() if len(w) > 6}) Matrix flatten and transpose
m = [[1, 2, 3], [4, 5, 6]]
print([x for row in m for x in row])
print([[row[i] for row in m] for i in range(3)]) Lazy sum of large range
total = sum(n * n for n in range(1, 10001) if n % 3 == 0)
print(total) Index students who passed
marks = {"Ada": 92, "Bob": 67, "Cia": 81, "Dan": 55}
passed = {name: score for name, score in marks.items() if score >= 80}
rank = sorted(((s, n) for n, s in passed.items()), reverse=True)
print(passed)
print(rank) Problem Solving Tricks
- Use a generator expression inside
sum/any/allto avoid temporary lists. - Ternary inside comps:
[("even" if n % 2 == 0 else "odd") for n in nums]. - Dict comps can rename keys:
{k.lower(): v for k, v in d.items()}. - Flatten one level:
[x for row in rows for x in row]. - Unique preserve-ish via dict comps in 3.7+:
list(dict.fromkeys(items)). - Avoid
[print(x) for x in xs]— that builds a useless list of Nones. - Prefer
str.joinwith a genexp:",".join(str(n) for n in nums). - Keep comps under ~2 clauses; beyond that, refactor to a loop or helper.
- Zip in comps:
{k: v for k, v in zip(keys, values)}.
Practice Programs List
- Rewrite a 5-line map/filter loop as a list comprehension.
- Build a set of unique vowels present in a sentence.
- Create a multiplication table as a nested list comprehension.
- Invert a dict with a comprehension (assume unique values).
- Use a generator expression to find if any number in a huge range is divisible by 7919.
- Flatten a list of tuples into a list of first elements.
- Filter product dicts to those with price < 100 using a dict comp.
- Compare memory of list vs generator for
range(1_000_000)transforms. - Write a nested comp, then rewrite it as nested loops — which reads better?
- Build
{filename: size}from a list of (name, size) pairs. - Extract digits from mixed strings with a filtered comprehension.