1.2.34 · D1Introduction to Programming (Python)

Foundations — List comprehensions — `[expr for x in iterable if condition]`

3,646 words17 min readBack to topic

Before you can read that one-liner, you must be fluent in the small pieces it is built from. This page assumes you know nothing and earns every symbol, one at a time, in the order they depend on each other. We will only assemble the full recipe in the final section, once every part has a meaning.


0a. What is a value? Numbers, strings, and =

The picture: a value is one physical object — a coin (5), a written word ("apple") — that you can hold, pass around, or drop into a box.


0b. The square brackets [ ] and the comma , — what a list even is

The picture: think of a row of numbered lockers, with a thin divider (the comma) between each pair. Locker 0 holds the first item, locker 1 the second, and so on (Python starts counting at zero, not one — remember that).

Figure — List comprehensions — `[expr for x in iterable if condition]`
Figure s01 — a list drawn as a row of numbered lockers. Each locker holds one item; the thin dividers are the commas; the index label under each locker counts from 0.


1. Variables and the name x — a sticky label

The picture: a luggage tag. The tag says x; it can be moved from one suitcase (value) to another. During a loop, the tag x gets re-stuck to each item in turn.


2. iterable, range(), and what "generator" means — the source of items

The picture: a Pez dispenser or a conveyor belt — you don't grab everything at once, you take the next item, then the next.

Figure — List comprehensions — `[expr for x in iterable if condition]`
Figure s02 — range(4) as a dispenser handing out 0, 1, 2, 3 in order; the greyed-out 4 shows the stop value is never produced.

See range() and iterables for the full story of what can feed the for slot.


3. The for loop, the colon :, and indentation — the engine

The picture: the colon is a doorway sign reading "loop body this way ↓", and the indentation is the walled-off room the sign points into. A factory worker takes each item off the belt in turn, does the indented job on it, and reaches for the next.

Figure — List comprehensions — `[expr for x in iterable if condition]`
Figure s03 — the for loop as a conveyor belt: items 0, 1, 2 arrive one at a time, the loop variable x becomes each in turn, and the body runs once per item.


4. .append() and the empty list [] — how a list grows

The picture: dropping one more apple into the back of the box each time.


5. Boolean values and condition — True / False

The picture: a light switch or a yes/no gate. True = gate open (let it through), False = gate shut (throw it away).


6. Expressions vs statements, and the ternary a if cond else b

The picture: an expression is a vending machine — put stuff in, a value comes out. A statement is a light switch — it acts, but you can't "hold" its result.

Figure — List comprehensions — `[expr for x in iterable if condition]`
Figure s04 — left: an expression (vending machine) always hands back a value, so it can fill the output slot; right: a statement (switch) acts but returns nothing, so it cannot.


7. ** and len() — the transform tools in the examples


Putting it together: reading [x**2 for x in range(10) if x % 2 == 0]

Now every piece is earned, so we can finally assemble the recipe [expr for x in iterable if condition] and read the parent's flagship example left to right, naming each part:

Fragment What you now know it means Built in
[ ... ] and its , building a new list of values, comma-separated §0a, §0b
x**2 the expr: an expression producing a value §6, §7
for x in range(10) the loop over an iterable, x re-labels each item §1, §2, §3
if x % 2 == 0 the Boolean guard keeping only survivors §5

You can read it as one English sentence: "the value x**2, for each x from 0 up to 9, but only if x is even."


Prerequisite map

value literal and = assignment

Square brackets and comma = a list

Variables a re-stickable name x

Iterables range and generator

colon and indentation block

The for loop engine

empty list and append

Booleans and conditions

power ** and len

Expression statement and ternary

List comprehension


Equipment checklist

Test yourself — cover the right side and answer each aloud before revealing.

What is a value, and what is a literal?
A value is one piece of data (a number, a string); a literal is that value written out directly in code, like 5 or "apple".
What does a single = do?
It assigns — sticks a name onto a value, e.g. x = 5. It is a command, not a question.
What does [ ] around comma-separated values build?
An ordered list — a box of values, each with a fixed position, counting from 0.
Is the comma part of an item's value?
No — it is pure syntax that separates one item from the next.
What is x in for x in ..., fixed or changing?
Changing — it re-attaches to each item in turn, one per pass.
Does a list comprehension's loop variable x leak into the outer scope?
No — in Python 3 it lives in the comprehension's private scope and does not overwrite an outer x of the same name.
What does range(4) produce?
0, 1, 2, 3 — starts at 0, stops before 4.
Is range a generator?
No — it is a reusable sequence object; you can loop it twice, index it, or take its length.
What is a generator in one phrase?
A one-shot, lazy iterable — it makes each item only when asked and is used up after one pass.
What is an iterable in one phrase?
Anything you can pull items out of one at a time, in order.
What does the colon : at the end of a for line do?
It announces that a block of code (the loop body) follows; the indented lines beneath it are that block.
What does a for loop do?
Runs its indented body once for each item of an iterable, with the loop variable set to that item.
Starting from r=[], what does r.append(7) do?
Adds 7 to the end, giving [7].
What two values can a Boolean be?
True or False only.
Difference between = and ==?
= assigns a value to a name; == asks "are these equal?" and returns a Boolean.
What does x % 2 == 0 test, and what caveat has % with negatives?
Whether x is even; % takes the sign of the divisor, so e.g. -7 % 3 is 2, not -1.
What is the syntax and evaluation order of a ternary a if cond else b?
Python evaluates cond first; if True the whole expression yields a, else it yields b — it always produces one value.
Why must the output expr be an expression, not a statement?
Because its produced value is what gets appended into the new list; a statement produces no value to store.
Can you omit the if guard?
Yes — [expr for x in iterable] keeps every item.
Where does a ternary a if cond else b fit, and why?
In the expr slot (before for), because it is an expression that yields a value.
What is 3**2?
9 — 3 raised to the power 2.

Connections

  • For loops — the engine this whole topic is sugar over.
  • range() and iterables — what feeds the for x in iterable slot.
  • Conditional expressions (ternary) — the expression-form if/else used inside expr.
  • map() and filter() — functional equivalents of transform (§7) and filter (§5).
  • Dictionary and set comprehensions — same foundations, different brackets.
  • Generator expressions — the lazy cousin; unlike range, truly one-shot (§2).
  • [[List comprehensions — `[expr for x in iterable if condition]` (index 1.2.34)|↑ Back to the parent topic]]