logo
26

Comprehensions

⏱️ 25 min

Comprehensions: Common Loops, Written Shorter

What You Might Be Wondering

"Do I have to use comprehensions to be Pythonic?"

No. Comprehensions are a readability tool, not a flex tool. Make sure you can read and maintain them first.

One-Line Definition

A comprehension is a concise "loop + condition + build new collection" expression.

Real-Life Analogy

Regular loops are like manual assembly. Comprehensions are like a template on a production line — faster when the rules are fixed.

Minimal Working Example

squares = [x * x for x in range(1, 6)]
print(squares)

Three Common Types

# list
list_even = [x for x in range(1, 11) if x % 2 == 0]

# dict
scores = {"Amy": 88, "Bob": 95, "Cara": 76}
passed = {name: s for name, s in scores.items() if s >= 80}

# set
vals = [1, 1, 2, 3, 3]
unique_sq = {x * x for x in vals}

When NOT to Use Comprehensions

  • Logic is more than one layer deep and hard to read
  • You need complex error handling
  • You need to inspect intermediate state for debugging

Quick Quiz (5 min)

  1. Generate a list of numbers from 1-100 divisible by 3.
  2. Convert ['alice', 'bob'] into {name: len(name)}.
  3. Use a set comprehension to deduplicate and square values.

Quiz Rubric & Grading Criteria

  • Direction: write runnable code that covers the core requirements and edge cases from the prompt.
  • Criterion 1 (Correctness): main flow produces correct results, key branches execute.
  • Criterion 2 (Readability): clear variable names, no excessive nesting.
  • Criterion 3 (Robustness): basic protection against empty values, type errors, or unexpected input.

Take-Home Task

Take a "regular loop that cleans a user list" and rewrite it as a comprehension. Compare readability.

Acceptance Criteria

You can independently:

  • Write list, dict, and set comprehensions
  • Judge when to use a comprehension vs. a regular loop
  • Keep code concise without sacrificing readability

Common Errors & Debugging Steps (Beginner Edition)

  • Error message looks like gibberish: read the last line for the error type (TypeError, NameError, etc.), then trace back to the offending line.
  • Not sure what a variable holds: drop a temporary print(variable, type(variable)) to check.
  • Changed code but nothing happened: make sure you saved the file, you're running the right file, and your terminal environment (venv) is correct.

Common Misconceptions

  • Misconception: converting every loop to a comprehension makes you more professional.

  • Reality: forcing complex logic into one line hurts maintainability.

  • Misconception: cramming multiple conditions into one comprehension is fine.

  • Reality: when readability drops, just write a normal loop.