← Lessons/Lists, Dicts & Comprehensions
← Lists, Dicts & Comprehensions

A comprehension

Learn

Comprehensions: an assembly line in one line

You'll constantly build a new list from an old one, transforming or filtering as you go. A list comprehension does it in one line. Read it as an assembly line: "take each item, keep it only if it passes the test, and collect the results":

ports = [22, 80, 443, 8080]
high = [p for p in ports if p > 1000]   # → [8080]

The same thing as a manual loop is three lines of append. The comprehension reads like the sentence you'd say out loud.

% is the remainder after division, so n % 2 == 0 is true exactly when n is even. sum(...) adds up a list of numbers.

Given nums = [1, 2, 3, 4, 5, 6], build evens with a comprehension that keeps only even numbers, print the list ([2, 4, 6]), and print sum: 12.

Interview prep

Reaching for a comprehension instead of a manual loop-and-append is a quick fluency signal.

When would you use a list comprehension over a for loop?

When you're building a new list by transforming or filtering an existing iterable — [f(x) for x in items if cond(x)]. It's more concise and usually faster than initializing an empty list and appending in a loop. For side effects (printing, writing) or complex logic, a plain loop is clearer.

$ python3 main.py
Loading...

Output

Run your solution to see its output here.