Editor

Python list comprehension MCQ questions with answers

Read the comprehension, predict the list: conditions, nesting and generators.

0 of 20 answered

  1. 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

    range(5) gives 0 to 4, and n ** 2 squares each one. The loop never reaches 5, so 25 is not in the list.

    Run this code in the editor
  2. 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 if clause keeps only the items for which n % 2 == 0 is true, in their original order. A comprehension filters but does not sort, and it collects n, not the result of the condition.

    Run this code in the editor
  3. 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 'education' that appear in 'aeiou': e, u, a, i and o, in the order they occur. vowels[:2] takes the first two of those.

    Run this code in the editor
  4. 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 editor
  5. Question 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 sum() adds them as they come, giving 18. range(1, 11) stops at 10, so 12 is not included.

    Run this code in the editor
  6. 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 for part of a comprehension needs something to loop over. An integer is not iterable, so Python raises TypeError; range(5) would give the numbers 0 to 4.

    Run this code in the editor
  7. 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: value pair 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.

  8. 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 * n squares each item. n * 2 doubles instead, curly braces make a set, and parentheses make a generator, not a list.

  9. 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 if ... else placed before for is 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.

    Run this code in the editor
  10. 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 for clauses 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.

    Run this code in the editor
  11. 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 sorted() returns in alphabetical order.

    Run this code in the editor
  12. 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 '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'.

    Run this code in the editor
  13. 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 if at the end of a comprehension cannot have an else, so the code does not even compile. To choose between two values, put the conditional expression before for: [x if x > 2 else 0 for x in range(5)].

    Run this code in the editor
  14. Question 14 · Medium

    Why does sum(x * x for x in range(10**6)) use less memory than sum([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 hands sum() one square at a time, so memory use stays small. Both give the same total.

  15. Question 15 · Medium

    In Python 3, what happens to a variable x defined before [x for x in range(3)] runs?

    Show the answer

    Answer: B, It keeps its value: the comprehension's x is local to the comprehension

    A comprehension has its own scope, so its loop variable neither leaks out nor overwrites a variable with the same name. A plain for loop is different: after for x in range(3), x is 2.

  16. 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 for clauses in one comprehension give a single flat list, and range(3) starts at 0, which fills the first row with zeros.

  17. 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 i over 0, 1 and 2 and builds one inner list for each. The inner one takes item i from every row, so each new row is a column of the original: the matrix is transposed.

    Run this code in the editor
  18. 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 sum() uses them all up, so the second finds nothing left and returns 0. A list comprehension in square brackets could be summed twice.

    Run this code in the editor
  19. 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 i, so the pairs are (1,1), (1,2), (1,3), (2,2), (2,3) and (3,3). The if keeps the pairs with an even sum, (1,1), (1,3), (2,2) and (3,3), whose products are 1, 3, 4 and 9.

    Run this code in the editor
  20. 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 k and v, which works for two-character strings: 'ab' gives 'a' and 'b'. 'efg' has three characters for two names, so ValueError is raised and no dictionary is made.

    Run this code in the editor

Keep going