Python Comprehensions Quiz for Coding Practice
Welcome to this ultimate Python comprehensions quiz! Here, we have compiled 30 multiple-choice questions based on list, set, and dictionary comprehensions in Python, which will cover basic to advanced concepts. This MCQs quiz will test your knowledge in comprehensions as well as level up your understanding level.
Whether youβre a beginner or an experienced Python programmer, this quiz is perfect for coding interviews, practices, and enhancing your knowledge in Python comprehensions. So, are you ready to score 30/30? Letβs see, how well do you really understand Python comprehensions? You will get the scorecard at the end of quiz. Letβs begin with question number 1.π
1. What does “comprehension” mean in Python?
A. A function used to read files.
B. A concise way of creating a new sequence, such as a list, set, dictionary, and generator from an existing sequence.
C. A loop that runs in reverse order.
D. A debugging method in Python
b
Comprehensions provide a shorter syntax to create new sequences, such as lists, sets, or dictionaries from existing iterables using a single line of code.
2. Which of the following is NOT a type of comprehension in Python?
A. List comprehension
B. Set comprehension
C. Tuple comprehension
D. Generator comprehension
c
Python does not support “tuple comprehension” directly. A generator expression looks similar but returns a generator, not a tuple.
3. What is the syntax for a basic list comprehension?
A. for x in list: x
B. [x for x in iterable]
C. (x in iterable)
D. {x: x for x in iterable}
b
The correct syntax for list comprehension is consists of square brackets ([ ]), which contain three parts: expression (or transform), iteration, and filter. The general syntax structure for a list comprehension in Python is as: new_list = [expression for iterating_var in iterable (or sequence)].
4. What is the output of the following list comprehension?
numbers = [1, 2, 3, 4] squared = [x ** 2 for x in numbers] print(squared)
A. [1, 4, 9, 16]
B. [1, 2, 3, 4]
C. [2, 4, 6, 8]
D. [1, 8, 27, 64]
a
The list comprehension squares each element in the list numbers, and produces [1, 4, 9, 16].
5. Which comprehension would create a set of even numbers from 0 to 9?
A. [x for x in range(10) if x % 2 == 0]
B. (x for x in range(10) if x % 2 == 0)
C. {x: x for x in range(10) if x % 2 == 0}
D. {x for x in range(10) if x % 2 == 0}
d
This is a set comprehension. Curly braces and filtering using if x % 2 == 0 give only even numbers.
6. What is the main advantage of using comprehension in Python?
A. Slower code execution
B. Improved code readability and shorter syntax
C. Increased memory usage
D. Difficult to reuse the code.
b
Comprehension make code more concise and easier to read. It often reducing multiple lines of loops by transforming complex code in a single line.
7. What does this list comprehension output?
nums = [5, 10, 15, 20] filtered = [x for x in nums if x > 10] print(filtered)
A. [5, 10]
B. [10, 15, 20]
C. [5, 10, 15]
D. [15, 20]
d
The list comprehension filters numbers greater than 10, resulting in [15, 20].
8. What will be the output of the following code?
result = [i for i in range(3) for j in range(2)] print(result)
A. [0, 1, 2]
B. [0, 0, 1, 1, 2, 2]
C. [0, 1, 0, 1, 0, 1]
D. [0, 0, 1, 2]
b
For each i in range(3), the inner loop for j in range(2) runs twice. So, each i is repeated twice.
9. What is the expected output of the following list comprehension in Python?
result = [x*2 for x in "Python" if x.lower() not in 'aeiou'] print(result)
A. [‘PP’, ‘tt’, ‘hh’, ‘nn’]
B. [‘yy’, ‘tt’, ‘hh’, ‘nn’]
C. [‘Py’, ‘th’, ‘n’]
D. [‘PP’, ‘yy’, ‘tt’, ‘hh’, ‘nn’]
d
The above list comprehension doubles consonants. Only vowels (a, e, i, o, u) are excluded.
10. What does this output if no error?
result = [x for x in range(10) if x % 2 == 0 if x % 3 == 0] print(result)
A. [0, 6]
B. [6]
C. [0, 3, 6, 9]
D. [0, 2, 4, 6, 8]
a
In the above code, the list comprehension creates a list of numbers from 0 to 9 that satisfy two conditions: x % 2 == 0 (the number is divisible by 2 (i.e., it’s even) and x % 3 == 0 (the number is divisible by 3). Only numbers that satisfy both conditions are included in the final list.
11. What will be the output of list comprehension if no error?
result = [x for x in [None, False, 0, '', [], {}] if x] print(result)
A. [None, False, 0, ”, [], {}]
B. [False, 0]
C. [None]
D. []
d
In the above code, the list comprehension checks the condition if x for each element. Since all elements are falsy, none of them pass this condition. Therefore, nothing is added to the new list and an empty list is returned.
12. What is the output of this set comprehension in Python code?
words = ["hello", "world", "python"] unique_chars = {char for word in words for char in word} print(unique_chars)
A. {‘hello’, ‘world’, ‘python’}
B. {‘h’, ‘e’, ‘l’, ‘o’}
C. {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’, ‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’}
D. {‘e’, ‘r’, ‘t’, ‘n’, ‘y’, ‘d’, ‘l’, ‘w’, ‘h’, ‘p’, ‘o’}
d
In this code, the set comprehension extract all unique characters from the list of words. The first loop (for word in words) iterates over each word in words. The second loop (for char in word) iterates over each character in the current word. Each individual character is added to the set. Since set does not store duplicate values, so it outputs the set of unique characters.
13. Which of the following is the correct dictionary comprehension to square numbers 1 to 4 as keys and values?
A. {x: x^2 for x in range(1, 5)}
B. {x: x**2 for x in range(1, 5)}
C. dict(x=x**2 for x in range(1, 5))
D. {x**2: x for x in range(1, 5)}
b
{x: x**2 for x in range(1, 5)} is the correct dictionary comprehension to square numbers 1 to 4 as keys and values because ** is the exponentiation operator in Python. Option A is incorrect because ^ is bitwise XOR.
14. Which of the following set comprehension filters the square of odd numbers?
A. {x**2 for x in numbers if x % 2 == 0}
B. {x**2 for x in numbers if x % 2}
C. {x**2 for x in numbers if x % 2 != 0}
D. {x^2 for x in numbers if x % 2 != 0}
c
The {x**2 for x in numbers if x % 2 != 0} squares only the odd numbers.
15. What is the output of this list comprehension with ternary operator?
numbers = [1, 2, 3, 4, 5] result = [x if x % 2 == 0 else x * 2 for x in numbers] print(result)
A. [1, 2, 3, 4, 5]
B. [1, 4, 3, 8, 5]
C. [2, 4, 6, 8, 10]
D. [2, 2, 6, 4, 10]
d
The above code doubles odd numbers and keeps even numbers unchanged. For each x in numbers, if x is even (x % 2 == 0), keep x as it is. Otherwise, multiply x by 2.
16. What is the expected output of the below nested list comprehension?
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] result = [x for row in matrix if sum(row) > 10 for x in row if x % 2 == 0] print(result)
A. [2, 6, 8]
B. [4, 6, 8]
C. [2, 4, 6, 8]
D. [4, 5, 6, 7, 8, 9]
b
This list comprehension filters and flattens values from a 2D list (matrix) based on two conditions. It keeps only rows whose sum is greater than 10. From those rows, it collects only the even numbers (x % 2 == 0). The first condition if sum(row) > 10 filters rows with sums > 10. So, [1, 2, 3] β sum = 6 β rejected, [4, 5, 6] β sum = 15 β accepted. and [7, 8, 9] β sum = 24 β accepted. Thus, only two rows [[4, 5, 6] and [7, 8, 9]are used. The second condition for x in row if x % 2 == 0 goes through each accepted row and pick even numbers. [4, 5, 6] β 4 and 6 are even and [7, 8, 9] β 8 is even. Thus, the output is only 4, 6, 8.
17. What does this dictionary comprehension output?
keys = ['a', 'b', 'a'] values = [1, 2, 3] result = {k: v for k, v in zip(keys, values)} print(result)
A. {‘a’: 1, ‘b’: 2, ‘a’: 3}
B. Error: Duplicate keys
C. {‘a’: 3, ‘b’: 2}
D. {‘a’: 1, ‘b’: 2}
c
We know that dictionary keys must be unique. The last value 3 for key ‘a’ overwrites the first value 1.
18. What will be the output when the set comprehension executes?
items = [[1], [2], [3], [4]] result = {x for x in items}
A. {[1], [2], [3]}
B. {1, 2, 3}
C. {1}
D. TypeError
d
Sets require elements to be hashable (immutable). Since lists are unhashable, so this raises TypeError.
19. What will be the output of this code if no error?
x = 1 result = [x := x + 1 for _ in range(3)] print(result)
A. [1, 2, 3]
B. [1, 1, 1]
C. [2, 3, 4]
D. SyntaxError
c
In the above code, the list comprehension contains the walrus operator (:=), which modify x in-place during each iteration. During each iteration, it increments x by 1 and returns or stores the updated value of x in the resulting list. Initialization: x = 1 (starting value). In the list comprehension, for _ in range(3) runs 3 times (the loop variable _ is a convention for unused variables). During first iteration, x = 1 + 1 = 2 β 2 is added to the list. During the second iteration, x = 2 + 1 = 3 β 3 is added to the list. Similarly, during third iteration, x = 3 + 1 = 4 β 4 is added to the list. The resulting list becomes [2, 3, 4].
20. What is the output of this set comprehension with generator?
gen = (x for x in range(5) if x % 2 == 0) result = {x * 2 for x in gen} print(result)
A. {0, 1, 2, 3, 4}
B. {0, 2, 4, 6, 8}
C. {0, 2, 4}
D. {0, 4, 8}
d
In this code, there is a generator expression to filter even numbers from 0 to 4. Then, a set comprehension multiply the resulting numbers by 2 and store them in a set. The range(5) function generates [0, 1, 2, 3, 4]. The condition x % 2 == 0 keeps even numbers [0, 2, 4]. A generator object gen yields 0, 2, 4 when iterated. The set comprehension result = {x * 2 for x in gen} iterates over gen, which gives 0, 2, 4. Each value is multiplied by 2, which results {0, 4, 8}. Since sets are unordered, so the order may vary.
21. What does this dictionary comprehension give the expected result?
numbers = [1, 2, 3, 4, 5, 6] result = {x: ('even' if x % 2 == 0 else 'odd') for x in numbers if x > 2} print(result)
A. {3: ‘odd’, 5: ‘odd’}
B. {4: ‘even’, 5: ‘odd’, 6: ‘even’}
C. {1: ‘odd’, 2: ‘even’, 3: ‘odd’, 4: ‘even’}
D. {3: ‘odd’, 4: ‘even’, 5: ‘odd’, 6: ‘even’}
d
The condition if x > 2 filters numbers (3, 4, 5). The value is ‘even’ or ‘odd’ based on parity.
22. What is the purpose of the using if clause in list comprehension?
A. Adds an element to the list.
B. Sorts the elements in the list.
C. Converts elements to uppercase.
D. Excludes an element from the list based on a condition.
d
The if clause in list comprehension acts as a filter. It determines which elements should be included in the final list.
23. What does the following nested dictionary comprehension output?
keys = ['a', 'b'] values = [1, 2] result = {k: {v: k * v} for k in keys for v in values} print(result)
A. {‘a’: {1: ‘a’}, ‘b’: {2: ‘bb’}}
B. {‘a’: {1: ‘a’, 2: ‘aa’}, ‘b’: {1: ‘b’, 2: ‘bb’}}
C. {‘a’: {1: 1}, ‘b’: {2: 4}}
D. {‘a’: 1, ‘b’: 2}
a
Outer Loop (for k in keys) iterates over keys [‘a’, ‘b’]. First iteration: k = ‘a’ and second iteration: k = ‘b’. For each k, the inner loop (for v in values) iterates over values = [1, 2]. First inner iteration: v = 1 and second inner iteration: v = 2.
24. What happens if you use the comprehension without assigning it to a variable?
A. It raises a syntax error.
B. It creates a list but doesn’t store it.
C. It modifies the original list in-place.
D. It returns a generator object.
b
If you use a comprehension without assigning it to a variable, the code will still run, with no syntax error. List is also created in the memory, but will not store and immediately discard if it’s not used.
25. What happens if the iterable is empty in the list comprehension?
A. It raises a ValueError.
B. It raises a SyntaxError.
C. It results in an infinite loop.
D. It creates an empty list.
d
If the iterable (e.g. [x * 2 for x in [ ]]) used in a list comprehension is empty, the comprehension simply has no elements to process, so it returns an empty list without any error.
26. What does the following Python code output if no error?
result = {x for x in "hello" if x in "world"} print(result)
A. {‘l’, ‘o’}
B. {‘h’, ‘e’}
C. {‘w’, ‘r’, ‘d’}
D. {‘l’, ‘o’, ‘d’}
a
‘hello’ and ‘world’ share the letters ‘l’ and ‘o’. The set removes duplicates automatically.
27. Under what circumstances would you opt for traditional loops over list comprehensions?
A. When the code needs to be more concise.
B. When the logic involves complex conditions.
C. In situations where performance is critical.
D. List comprehension is always preferable.
b
The list comprehensions are great for concise and simple transformations, while traditional loops (like for or while) are often better in the complex scenarios.
28. What is the primary difference between [x for x in range(3)] and (x for x in range(3))?
A. The first is a generator, the second a list.
B. The first creates a list in memory, the second a lazy generator.
C. Both are functionally identical.
D. None of the above
b
[x for x in range(3)] creates a list in the memory while (x for x in range(3)) is a lazy generator.
29. In a dictionary comprehension {k:v for k,v in iterable}, what happens if duplicate keys occur?
A. Raises a KeyError.
B. Keeps the first occurrence.
C. Keeps the last occurrence.
D. Creates a list of values for that key.
c
If duplicate keys occur in a dictionary comprehension {k:v for k,v in iterable}, it keeps the last occurrence.
30. What does this comprehension output?
data = ["1", "2", None, "3"] result = [int(x) for x in data if x is not None] print(result)
A. Creates a generator
B. Raises TypeError on None
C. [1, 2, None, 3]
D. Filters None and converts to integers
d
The list comprehension [int(x) for x in data if x is not None] has three parts. The first part for x in data iterates over each element in data. The second part if x is not None filters out None value and the third part int(x) converts the remaining (non-None) strings to integers.
Quiz Results
0
Total Questions
0
Correct Answers
0
Incorrect Answers
0%
Score