You already know a loop — initialize an empty list, iterate, append, return. This week you learn the one-line version: [x*2 for x in nums] does the same thing in an expression you can read left to right. Every comprehension has a loop-body twin; you'll write both and watch them produce identical results.
Is the comprehension actually doing anything different under the hood, or is it just shorter syntax?
Purely shorter syntax. Python compiles it to roughly the same bytecode as the explicit loop. What changes is what a reader sees: a comprehension says "this is a transformation" — no mutable state, no side effects, one expression. Loops can do many things; comprehensions do exactly one.
And dict and set comprehensions are the same idea, just different brackets?
Same idea, different output shape. [] makes a list, {k: v for ...} makes a dict, {x for ...} makes a set. Five lessons this week: basic list comprehension, filter-and-transform, dict comprehension, set comprehension, and a capstone combining all three. By Friday, the "build an empty list and append" reflex is gone.
[x*2 for x in nums]if clause{word: length} dict with a dict comprehensionGoal: by Friday, [expr for x in xs if cond] is muscle memory.
7 lessons this week
You already know a loop — initialize an empty list, iterate, append, return. This week you learn the one-line version: [x*2 for x in nums] does the same thing in an expression you can read left to right. Every comprehension has a loop-body twin; you'll write both and watch them produce identical results.
Is the comprehension actually doing anything different under the hood, or is it just shorter syntax?
Purely shorter syntax. Python compiles it to roughly the same bytecode as the explicit loop. What changes is what a reader sees: a comprehension says "this is a transformation" — no mutable state, no side effects, one expression. Loops can do many things; comprehensions do exactly one.
And dict and set comprehensions are the same idea, just different brackets?
Same idea, different output shape. [] makes a list, {k: v for ...} makes a dict, {x for ...} makes a set. Five lessons this week: basic list comprehension, filter-and-transform, dict comprehension, set comprehension, and a capstone combining all three. By Friday, the "build an empty list and append" reflex is gone.
[x*2 for x in nums]if clause{word: length} dict with a dict comprehensionGoal: by Friday, [expr for x in xs if cond] is muscle memory.