[0]4[1]1[2]5[3]2numsnif n > 2n * 101nums = [4, 1, 5, 2]2big = [3 n * 104 for n in nums5 if n > 2][0]40[1]504 > 2 True4 * 10 = 401 > 2 False5 > 2 True5 * 10 = 502 > 2 False[4, 1, 5, 2]444152
Code card: tens.py; the highlighted lines are the part at workMemory cells: the list nums, the name n and the new listGate: the if clause, n > 2Press: the expression, n * 10A list comprehension builds a new list from an old one: big = [n * 10 for n in nums if n > 2]. Each step lights the parts it is about. A value hops from nums into n (the for clause), into the gate (the if clause) and, if it passes, into the press (the expression); a new cell then settles onto the new list. Values that fail the test drop away. At the end the name big is given to the finished list, n fades away, and lines 2 to 5 change into the same for loop.

The recipe

  1. Line 1 makes a list named nums: four numbers inside square brackets, kept in order. Each item sits at a position, its index, counting from 0. Our job: build a new list from it.

One item at a time

The result

Try it yourself

;; step 1/10 · line 1
>>> nums = [4, 1, 5, 2]
>>> nums[0]          # indexes count from 0
4
>>> len(nums)
4

The comprehension is split over four lines so each part gets its own line; Python joins lines inside brackets, so it is the same as big = [n * 10 for n in nums if n > 2]. For each item Python runs the clauses in the order for, then if, then the expression, even though the expression is written first.