CodeBlanks Logo Icon CodeBlanks

Comprehension basics

Learn comprehensions with [x for x in xs].

Comprehension basics

List comprehension is a short and readable way to build a list. Instead of a loop and append, you write it in one line:

squares = [n * n for n in [1, 2, 3]]
# [1, 4, 9]

The shape is: [expression for variable in list]. The expression is computed for each item and added to the result. This is shorter and faster than a classic for loop.

Prefer comprehension when it stays readable; if it grows too complex, a loop may be clearer.

Comprehension replaces a for loop

You can get the same result with a classic for loop:

squares = []
for n in [1, 2, 3]:
    squares.append(n * n)

Comprehension reduces these three lines to one. Which one to use is a matter of taste and readability.

In nested loops, comprehension can become complex; then a for loop may be clearer.

Practice Write a tripling comprehension

Assign to triples a comprehension that multiplies each item of [1, 2, 3, 4] by 3. Then print print(triples).

Starter code

main.py
# Triple with a comprehension

Sample solution

main.py
triples = [n * 3 for n in [1, 2, 3, 4]]
print(triples)

Expected output

[3, 6, 9, 12]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which produces the list [2, 4, 6]?

  • [x * 2 for x in [1, 2, 3]] Correct answer
  • [x for x in [2, 4, 6]]
  • [x + 2 for x in [1, 2, 3]]
  • [x * 2 for x in [2, 4, 6]]

Explanation: [x * 2 for x in [1, 2, 3]] doubles each item: [2, 4, 6].

2 Complete the comprehension

Question
doubles = [n * ____ for n in [1, 2, 3]]
Answer
doubles = [n * 2 for n in [1, 2, 3]]

Explanation: The expression needs a constant multiplier.

3 Match the comprehension parts

Term Meaning
[...] List comprehension
for Loop keyword
expression Per-item computation
in Source keyword

All lessons in Beginner