Comprehensions — Practice Questions
50 questions. Try each one yourself before checking the answer.
Build a list of squares for numbers 1 to 5 using a list comprehension.
Build a list of only the EVEN numbers from 1 to 20 using a list comprehension with an if clause.
Given word = "python", build a list of its individual characters using a list comprehension.
Build a dictionary mapping numbers 1 to 5 to their squares, using a dictionary comprehension.
Given numbers = [1, 2, 2, 3, 3, 3, 4], build a set of unique values using a set comprehension.
Given strings = ["1", "2", "3"], build a list of ints from them using a list comprehension and int().
Build the list of cubes for 1 to 5 TWO ways: once with a for loop and .append(), once with a list comprehension. Confirm both produce the same result.
Given words = ["apple", "banana", "kiwi"], build a list of each word's length using a list comprehension and len().
Given words = ["apple", "banana", "kiwi"], build a list of each word converted to uppercase using a list comprehension and .upper().
Build a list labeling numbers 1-10 as "Even" or "Odd" using a list comprehension with an inline if/else EXPRESSION (a ternary, not a filter).
Given matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], flatten it into a single flat list using a NESTED list comprehension (two for clauses).
Given scores = {"Alice": 88, "Bob": 45, "Carol": 92}, build a dict containing only students who scored 40+, using a dict comprehension with an if.
Given word = "mississippi", build a set of only its VOWEL characters using a set comprehension with an if.
Given colors = ["red", "green", "blue"], build a list of "index: color" strings using a list comprehension over enumerate().
Given names = ["Alice", "Bob"] and scores = [88, 92], build a list of "name: score" strings using a list comprehension over zip().
Build a list of (n, n**2) tuples for numbers 1 to 5 using a list comprehension.
Given country_codes = {"IN": "India", "US": "United States"}, build the INVERTED dictionary (name -> code) using a dict comprehension.
Build a 3x3 matrix (list of lists) where matrix[i][j] = i * 3 + j, using a nested list comprehension.
Build a list of numbers from 1 to 50 that are divisible by BOTH 3 AND 5, using a list comprehension with and in the condition.
Given prices = {"Pen": 10.5, "Notebook": 45.0, "Eraser": 5.75}, build a list of formatted "item: $price" strings using a list comprehension over .items().
Given numbers = [4, -2, 7, -9, 10, 3], build a list of only the POSITIVE numbers using a list comprehension.
Given sentence = "the quick brown fox", build a dict mapping each word to its length, using a dict comprehension.
Given text = "the cat sat on the mat", build a dict counting how many times each unique word appears, using a dict comprehension over the set of unique words plus .count().
Given emails = ["a@x.com", "b@y.com", "c@x.com"], build a list of just the domains using a list comprehension and .split("@").
Given scores = {"Alice": 88, "Bob": 45, "Carol": 92, "David": 30}, build a dict mapping each name to "Pass"/"Fail" using a dict comprehension with a ternary expression.
Given groups = [[1, 2], [3, 4, 5], [6]], flatten it into a single list using a nested list comprehension.
Given words = ["Apple", "avocado", "Banana", "blueberry", "Cherry"], build a set of the unique FIRST LETTERS (lowercased) using a set comprehension.
Given matrix = [[1, 2, 3], [4, 5, 6]], build its transpose using a nested list comprehension (no zip()).
Given numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], build a list containing the SQUARE of only the even numbers, using one list comprehension with both a filter and a transform.
Given products = {"Pen": 10.5, "Notebook": 45.0}, build a list of aligned, formatted strings for each product using a list comprehension.
Build a full multiplication table (rows 1-5, columns 1-5) as a list of lists, using a single nested list comprehension.
Given nested = [[1, 2], [3, [4, 5]], [6]] (irregularly nested, ONE extra level in the middle), flatten only the OUTER level with a nested comprehension, and note in a comment why the deeper [4, 5] stays nested.
Given students = {"Alice": 88, "Bob": 35, "Carol": 92, "David": 28}, build a dict of ONLY passing students (40+), with their names uppercased as keys, using a single dict comprehension combining filter + transform.
Given list_a = [1, 2, 3, 4, 5] and list_b = [3, 4, 5, 6, 7], find their common elements using a set comprehension, and confirm it matches set(list_a) & set(list_b).
Given numbers = [4, -9, 16, -25, 36], build a list of the square roots of only the numbers whose ABSOLUTE VALUE exceeds 10, using the walrus operator (:=) to avoid computing abs(n) twice per element.
Given matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], compute its transpose TWO ways — a nested list comprehension, and list(zip(*matrix)) — and confirm they produce equivalent results.
Given pairs = [("a", 1), ("b", 2), ("a", 3)], build a dict from them using a dict comprehension, and explain in a comment what happens with the DUPLICATE key "a".
Given a 3-level-deep nested comprehension that's hard to read, refactor it into an explicit set of loops, demonstrating both produce the same flattened result.
Given numbers = range(1, 16), build a FizzBuzz-style list using a list comprehension with a NESTED ternary expression ("FizzBuzz"/"Fizz"/"Buzz"/the number).
The following code raises a NameError when printing n after the comprehension runs. Find and explain the bug (there's nothing to "fix" in the comprehension itself — only in the expectation).
squares = [n ** 2 for n in range(5)]
print(squares)
print(n)Build a "Data Cleaner". Given a list of raw, messy strings ([" Alice ", "", "BOB", " ", "carol"]), use a chain of list comprehensions to strip whitespace, title-case, and remove empty entries.
Build a "Word Length Analyzer". Given a paragraph, build a dict comprehension mapping each unique word to its length, then find the longest word using max() on that dict.
Build a "Matrix Toolkit" using comprehensions: generate a 4x4 identity matrix, then transpose it, both via nested list comprehensions.
Build an "Inventory Filter". Given inventory = {"Pen": 50, "Notebook": 5, "Eraser": 2, "Stapler": 30}, build a dict comprehension of items with stock BELOW a reorder_threshold.
Build a "Grade Converter". Given scores = {"Alice": 92, "Bob": 78, "Carol": 65, "David": 45}, build a dict comprehension mapping each name to a letter grade (A/B/C/F) using a nested ternary expression.
Explain when a comprehension is the RIGHT tool versus when an explicit loop is better (side effects, multi-step logic, exception handling per item), demonstrating one example of each.
Demonstrate concretely that a comprehension's loop variable does NOT leak into the enclosing scope (a Python 3 change from Python 2), contrasting it with a regular for loop which DOES leak its variable.
Explain why list comprehensions are generally slightly faster than an equivalent for loop with .append(), and demonstrate measuring both with timeit.
A common code-review guideline: "comprehensions with more than 2 for clauses or 2 conditions should usually become a function." Demonstrate by refactoring an overloaded comprehension into a well-named generator function.
Build a "Comprehension Mastery Report" — the most complete demonstration in this module. Given students = {"Alice": 92, "Bob": 45, "Carol": 78, "David": 30}, use: a list comprehension (passing names), a dict comprehension (letter grades), a set comprehension (unique first letters of passing names), and a nested comprehension (a small grade-distribution matrix) — all printed in a labeled report.
Still stuck on something?
Book a free 1-on-1 session and we'll work through it together.
Book a Free Session