Python list comprehension MCQ questions with answers
Read the comprehension, predict the list: conditions, nesting and generators.
0 of 20 answered
Question 1 · Easy
What is the output of this code?
squares = [n ** 2 for n in range(5)] print(squares)
Show the answer
Answer: A
Run this code in the editorrange(5)gives 0 to 4, andn ** 2squares each one. The loop never reaches 5, so 25 is not in the list.Question 2 · Easy
What is the output of this code?
nums = [3, 8, 5, 12, 7, 10] evens = [n for n in nums if n % 2 == 0] print(evens)
Show the answer
Answer: B
The
Run this code in the editorifclause keeps only the items for whichn % 2 == 0is true, in their original order. A comprehension filters but does not sort, and it collectsn, not the result of the condition.Question 3 · Easy
What is the output of this code?
word = 'education' vowels = [ch for ch in word if ch in 'aeiou'] print(len(vowels), vowels[:2])
Show the answer
Answer: C
The comprehension keeps the characters of
Run this code in the editor'education'that appear in'aeiou': e, u, a, i and o, in the order they occur.vowels[:2]takes the first two of those.Question 4 · Easy
What is the output of this code?
names = ['Ann', 'Bob', 'Chris'] lengths = {name: len(name) for name in names} print(lengths)
Show the answer
Answer: D
In a dictionary comprehension the part before the colon is the key and the part after it is the value, so each name maps to its length. Equal values are fine; only keys must be unique.
Run this code in the editorQuestion 5 · Easy
What is the output of this code?
print(sum(x for x in range(1, 11) if x % 3 == 0))
Show the answer
Answer: B
The generator expression yields the multiples of 3 from 1 to 10: 3, 6 and 9, and
Run this code in the editorsum()adds them as they come, giving 18.range(1, 11)stops at 10, so 12 is not included.Question 6 · Easy
Which error does this code raise?
doubled = [x * 2 for x in 5]
Show the answer
Answer: B, TypeError: 'int' object is not iterable
The
Run this code in the editorforpart of a comprehension needs something to loop over. An integer is not iterable, so Python raisesTypeError;range(5)would give the numbers 0 to 4.Question 7 · Easy
What type of object does
{n: n * 2 for n in range(3)}create?Show the answer
Answer: C, A dictionary
Curly braces with a
key: valuepair make a dictionary comprehension, here{0: 0, 1: 2, 2: 4}. Without the colon,{n for n in range(3)}would be a set comprehension.Question 8 · Easy
Which expression turns
nums = [1, 2, 3]into the list[1, 4, 9]?Show the answer
Answer: D
Square brackets make a list, and
n * nsquares each item.n * 2doubles instead, curly braces make a set, and parentheses make a generator, not a list.Question 9 · Medium
What is the output of this code?
nums = [1, 2, 3, 4] labels = ['even' if n % 2 == 0 else 'odd' for n in nums] print(labels)
Show the answer
Answer: C
An
Run this code in the editorif ... elseplaced beforeforis a conditional expression that picks a value for every item; it does not filter. So there is one label per number, starting with'odd'for 1.Question 10 · Medium
What is the output of this code?
matrix = [[1, 2], [3, 4], [5, 6]] flat = [x for row in matrix for x in row] print(flat)
Show the answer
Answer: D
The
Run this code in the editorforclauses run in the order written, like nested loops: the first takes each row, the second takes each item of that row. One flat list comes out, row by row.Question 11 · Medium
What is the output of this code?
words = ['apple', 'avocado', 'banana', 'blueberry', 'cherry'] initials = {w[0] for w in words} print(len(initials), sorted(initials))
Show the answer
Answer: A
Curly braces without a colon make a set comprehension, and a set keeps each value once. Five words give only three different first letters, which
Run this code in the editorsorted()returns in alphabetical order.Question 12 · Medium
What is the output of this code?
grades = {'Ann': 'A', 'Bob': 'B', 'Cat': 'A'} by_grade = {g: name for name, g in grades.items()} print(by_grade)
Show the answer
Answer: B
Swapping makes the grades the keys, and
Run this code in the editor'A'comes up twice. The later pair overwrites the value, so'A'maps to'Cat', but the key stays where it was first inserted, before'B'.Question 13 · Medium
Which error does this code raise?
values = [x for x in range(5) if x > 2 else 0]
Show the answer
Answer: A, SyntaxError: invalid syntax
A filtering
Run this code in the editorifat the end of a comprehension cannot have anelse, so the code does not even compile. To choose between two values, put the conditional expression beforefor:[x if x > 2 else 0 for x in range(5)].Question 14 · Medium
Why does
sum(x * x for x in range(10**6))use less memory thansum([x * x for x in range(10**6)])?Show the answer
Answer: A, The generator expression produces one value at a time instead of building the whole list first
Square brackets build the full list of a million squares in memory before
sum()starts. The generator expression handssum()one square at a time, so memory use stays small. Both give the same total.Question 15 · Medium
In Python 3, what happens to a variable
xdefined before[x for x in range(3)]runs?Show the answer
Answer: B, It keeps its value: the comprehension's
xis local to the comprehensionA comprehension has its own scope, so its loop variable neither leaks out nor overwrites a variable with the same name. A plain
forloop is different: afterfor x in range(3),xis 2.Question 16 · Medium
Which expression builds the table
[[1, 2, 3], [2, 4, 6], [3, 6, 9]]?Show the answer
Answer: C
A comprehension inside another one builds a list of lists, with the inner one making each row. Two
forclauses in one comprehension give a single flat list, andrange(3)starts at 0, which fills the first row with zeros.Question 17 · Hard
What is the output of this code?
matrix = [[1, 2, 3], [4, 5, 6]] result = [[row[i] for row in matrix] for i in range(3)] print(result)
Show the answer
Answer: C
The outer comprehension runs
Run this code in the editoriover 0, 1 and 2 and builds one inner list for each. The inner one takes itemifrom every row, so each new row is a column of the original: the matrix is transposed.Question 18 · Hard
What is the output of this code?
gen = (n * 2 for n in range(4)) print(sum(gen), sum(gen))
Show the answer
Answer: D
A generator produces its values only once. The first
Run this code in the editorsum()uses them all up, so the second finds nothing left and returns 0. A list comprehension in square brackets could be summed twice.Question 19 · Hard
What is the output of this code?
products = [i * j for i in range(1, 4) for j in range(i, 4) if (i + j) % 2 == 0] print(products)
Show the answer
Answer: D
The inner loop starts at
Run this code in the editori, so the pairs are (1,1), (1,2), (1,3), (2,2), (2,3) and (3,3). Theifkeeps the pairs with an even sum, (1,1), (1,3), (2,2) and (3,3), whose products are 1, 3, 4 and 9.Question 20 · Hard
Which error does this code raise?
pairs = ['ab', 'cd', 'efg'] lookup = {k: v for k, v in pairs} print(lookup)
Show the answer
Answer: A, ValueError: too many values to unpack (expected 2)
Each string is unpacked into
Run this code in the editorkandv, which works for two-character strings:'ab'gives'a'and'b'.'efg'has three characters for two names, soValueErroris raised and no dictionary is made.
Keep going
- Read the lesson behind these questions: Comprehensions in the PythonBook
- Next topic: Python functions MCQ questions with answers
- Before this: Python set MCQ questions with answers
- Write the code yourself in the Python coding challenges, which check your solution with tests.