This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python List Comprehensions, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
What does [n * 2 for n in range(3)] produce?
Answer: [0, 2, 4]
Why: range(3) yields 0, 1, 2; each value is multiplied by 2.
Which clause filters values in a comprehension?
Answer: if
Why: The if clause keeps only values that satisfy the condition.
Which syntax builds a dictionary comprehension?
Answer: {k: v for k, v in items}
Why: A dictionary comprehension uses braces and a key: value expression.
What does [x for x in "abc"] produce?
Answer: ['a', 'b', 'c']
Why: Iterating over a string yields one-character strings.
Complete the operator that squares each number.
squares = [n ____ n for n in range(4)]
print(squares)Answer: *
Why: n * n multiplies each value by itself.
Complete the clause that keeps only even values.
nums = [1, 2, 3, 4]
evens = [n for n in nums ____ n % 2 == 0]
print(evens)Answer: if
Why: The if clause filters the values produced by the for clause.
Complete the function that provides each word's length.
words = ["a", "bb"]
lengths = {word: ____(word) for word in words}
print(lengths)Answer: len
Why: len(word) returns the number of characters in the word.
Complete the nested loop keyword.
pairs = [(x, y) ____ x in [1, 2] for y in [3, 4]]
print(pairs)Answer: for
Why: The second for clause produces the inner values.
What does this code print?
print([n + 1 for n in [1, 2, 3]])Answer: [2, 3, 4]
Why: Each value is increased by one.
What does the program output?
print([n for n in range(6) if n % 2 == 0])Answer: [0, 2, 4]
Why: The comprehension keeps 0, 2, and 4.
What appears on the screen?
print({n: n * n for n in range(3)})Answer: {0: 0, 1: 1, 2: 4}
Why: The dictionary maps 0, 1, and 2 to their squares.
What is printed?
print([len(w) for w in ["a", "bb", "ccc"]])Answer: [1, 2, 3]
Why: The lengths are 1, 2, and 3.
Try the questions first
Open the practice page for Python List Comprehensions and answer the same 12 questions with instant feedback.