How does the four-line create-loop-append-return pattern collapse into a single bracketed expression — and where does the filter go?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
Here is the long way to build a list, written out in full:
result = [] for e in numbers: result.append(e * 3)
Build that exact same list in one line with a list comprehension over numbers. Assign it to tripled.
The four-line build-a-list pattern in one line
Write square_list with its empty list, loop, append and return, then the single line Lnew = [e**2 for e in L], and read the comprehension aloud in English.
The optional if filter
Write square_evens with if e%2 == 0 inside the loop, then the one-liner [e**2 for e in L if e%2 == 0], and record where the test sits in the expression.
The general form and what it buys you
Write [expr(e) for e in old_list if test(e)] next to its long-form function, and record the claim that comprehensions gain readability rather than speed and suit simple list construction.