All lessons

Power Tools: map, filter & Comprehensions

9 min · Python

Python's shortcuts for transforming and filtering a list in one line.

Python · Power Tools: map, filter & Comprehensions0/5 cleared

Enemy 1 of 5

This builds a list of squares in one line, with no loop and no append. Press Run to see the squares of 0 through 4.

Why this works

By now you've written plenty of loops that build a new list by starting with an empty one and calling .append() inside a for loop. That pattern is so common in Python that the language has a dedicated shorthand for it: the list comprehension.

A list comprehension builds a new list in a single line: [expression for item in iterable]. It reads almost like a sentence ("give me expression, for every item in iterable") and produces exactly the same result as the equivalent multi-line for loop with .append(), just more compactly and, once you're used to reading it, more clearly.

Run this to build a list of squares without writing out the loop.

You
Binary Treant
Loading editor…
Target output: [0, 1, 4, 9, 16]