Comprehensions, map() and filter()
Interactive lab
Try it: Comprehensions, map() and filter()
That [expr for x in xs if cond] is a loop: for each item Python tests the condition and only then evaluates the expression and appends it — the same result as map() and filter(), a dict comprehension, or a nested pair of for clauses.
How it works
- Take the next x from xs (with two for clauses: every y for each x).
- Evaluate the if test; when it is False nothing is produced for this item.
- Otherwise evaluate the expression and append it (a dict comprehension sets result[key] = value; a repeated key overwrites but keeps its place).
- map(f, xs) applies f to every item; filter(f, xs) keeps the items where f(x) is truthy.
Default run (12 steps): result = [x * 10 for x in xs if x > 4] — Python runs this as a loop over 6 items. … The loop is finished: result = [80, 50, 120, 70] (4 items).
Simplified: Expressions and tests come from a fixed menu of templates with editable numbers over up to 10 ints (and 6 for the second list); no learner code is evaluated.
Educational simulation
Loading the simulation…