Skip to main content

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.

L1

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.
FormResultExample idea
ListOrdered sequenceSquares of numbers
SetUnique valuesUnique lengths of words
DictKey-value mapWord → length
GeneratorLazy iteratorStream 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, max to 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 for clauses 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 for loops.
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 + lambda for simple transforms.
  • filter + list can be replaced with if in a comprehension.
  • Keep map/filter when 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 for target: 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)
L2

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/continue needs, 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))
L3

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.

L4

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)
L5

Problem Solving Tricks

  • Use a generator expression inside sum/any/all to 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.join with 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)}.
L6

Practice Programs List

  1. Rewrite a 5-line map/filter loop as a list comprehension.
  2. Build a set of unique vowels present in a sentence.
  3. Create a multiplication table as a nested list comprehension.
  4. Invert a dict with a comprehension (assume unique values).
  5. Use a generator expression to find if any number in a huge range is divisible by 7919.
  6. Flatten a list of tuples into a list of first elements.
  7. Filter product dicts to those with price < 100 using a dict comp.
  8. Compare memory of list vs generator for range(1_000_000) transforms.
  9. Write a nested comp, then rewrite it as nested loops — which reads better?
  10. Build {filename: size} from a list of (name, size) pairs.
  11. Extract digits from mixed strings with a filtered comprehension.