CodeBlanks Logo Icon CodeBlanks

Summary - List comprehension

Combine comprehension and generator expressions to write a number processor.

Summary - List comprehension

In this group we covered comprehension, filtering, dict/set, nested and generator.

  • List: [expr for n in list]
  • Filter: add ... if condition
  • Dict: {key: value for ...}
  • Set: {expr for ...}
  • Generator: (expr for ...)

Now two tasks combine these concepts.

Practice Squares of even numbers

Assign to even_squares a comprehension that squares the even numbers from [1, 2, 3, 4, 5, 6]. Then print print(even_squares).

Starter code

main.py
# Square the even numbers with a comprehension

Sample solution

main.py
even_squares = [n * n for n in [1, 2, 3, 4, 5, 6] if n % 2 == 0]
print(even_squares)

Expected output

[4, 16, 36]

Practice Dict and sum together

Assign to squares a dict comprehension holding n: n * n for each n in [1, 2, 3]. Assign sum(squares.values()) to total. Then print print(squares, total).

Starter code

main.py
# Dict comprehension and sum together

Sample solution

main.py
squares = {n: n * n for n in [1, 2, 3]}
total = sum(squares.values())
print(squares, total)

Expected output

{1: 1, 2: 4, 3: 9} 14

Questions and answers

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

1 Which comprehension gives [6, 8]?

  • [n * 2 for n in [1, 2, 3, 4]]
  • [n * 2 for n in [1, 2, 3, 4] if n > 2] Correct answer
  • [n + 2 for n in [1, 2, 3, 4] if n > 2]
  • [n for n in [6, 8]]

Explanation: 3 and 4 are taken, doubled to [6, 8].

2 Complete max with a generator

Question
biggest = max(n * n for n in [____])
Answer
biggest = max(n * n for n in [5])

Explanation: For [1, 2, 3, 4, 5] the largest square is 25.

All lessons in Beginner