Python · Functional Python

Comprehensions — Practice Questions

50 questions. Try each one yourself before checking the answer.

Q1List ComprehensionEasy

Build a list of squares for numbers 1 to 5 using a list comprehension.

Q2List Comprehension with FilterEasy

Build a list of only the EVEN numbers from 1 to 20 using a list comprehension with an if clause.

Q3List ComprehensionEasy

Given word = "python", build a list of its individual characters using a list comprehension.

Q4Dict ComprehensionEasy

Build a dictionary mapping numbers 1 to 5 to their squares, using a dictionary comprehension.

Q5Set ComprehensionEasy

Given numbers = [1, 2, 2, 3, 3, 3, 4], build a set of unique values using a set comprehension.

Q6List ComprehensionEasy

Given strings = ["1", "2", "3"], build a list of ints from them using a list comprehension and int().

Q7Comprehension vs LoopEasy

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.

Q8List ComprehensionEasy

Given words = ["apple", "banana", "kiwi"], build a list of each word's length using a list comprehension and len().

Q9List ComprehensionEasy

Given words = ["apple", "banana", "kiwi"], build a list of each word converted to uppercase using a list comprehension and .upper().

Q10Conditional ExpressionEasy

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

Q11Nested ComprehensionMedium

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

Q12Dict Comprehension with ConditionMedium

Given scores = {"Alice": 88, "Bob": 45, "Carol": 92}, build a dict containing only students who scored 40+, using a dict comprehension with an if.

Q13Set Comprehension with ConditionMedium

Given word = "mississippi", build a set of only its VOWEL characters using a set comprehension with an if.

Q14enumerate()Medium

Given colors = ["red", "green", "blue"], build a list of "index: color" strings using a list comprehension over enumerate().

Q15zip()Medium

Given names = ["Alice", "Bob"] and scores = [88, 92], build a list of "name: score" strings using a list comprehension over zip().

Q16List of TuplesMedium

Build a list of (n, n**2) tuples for numbers 1 to 5 using a list comprehension.

Q17Dict ComprehensionMedium

Given country_codes = {"IN": "India", "US": "United States"}, build the INVERTED dictionary (name -> code) using a dict comprehension.

Q18Nested ComprehensionMedium

Build a 3x3 matrix (list of lists) where matrix[i][j] = i * 3 + j, using a nested list comprehension.

Q19Multiple ConditionsMedium

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.

Q20Comprehension over items()Medium

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().

Q21Real-WorldMedium

Given numbers = [4, -2, 7, -9, 10, 3], build a list of only the POSITIVE numbers using a list comprehension.

Q22Real-WorldMedium

Given sentence = "the quick brown fox", build a dict mapping each word to its length, using a dict comprehension.

Q23Real-WorldMedium

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().

Q24Real-WorldMedium

Given emails = ["a@x.com", "b@y.com", "c@x.com"], build a list of just the domains using a list comprehension and .split("@").

Q25Real-WorldMedium

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.

Q26Nested ComprehensionMedium

Given groups = [[1, 2], [3, 4, 5], [6]], flatten it into a single list using a nested list comprehension.

Q27Real-WorldMedium

Given words = ["Apple", "avocado", "Banana", "blueberry", "Cherry"], build a set of the unique FIRST LETTERS (lowercased) using a set comprehension.

Q28Nested ComprehensionMedium

Given matrix = [[1, 2, 3], [4, 5, 6]], build its transpose using a nested list comprehension (no zip()).

Q29Filter + TransformMedium

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.

Q30FormattingMedium

Given products = {"Pen": 10.5, "Notebook": 45.0}, build a list of aligned, formatted strings for each product using a list comprehension.

Q31Nested ComprehensionHard

Build a full multiplication table (rows 1-5, columns 1-5) as a list of lists, using a single nested list comprehension.

Q32Nested ComprehensionHard

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.

Q33Dict ComprehensionHard

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.

Q34Set ComprehensionHard

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

Q35Walrus in ComprehensionHard

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.

Q36Nested Comprehension vs zip()Hard

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.

Q37Dict Comprehension GotchaHard

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

Q38ReadabilityHard

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.

Q39Conditional ExpressionHard

Given numbers = range(1, 16), build a FizzBuzz-style list using a list comprehension with a NESTED ternary expression ("FizzBuzz"/"Fizz"/"Buzz"/the number).

Q40DebuggingHard

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)
Q41Mini-ProjectMini-Project

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.

Q42Mini-ProjectMini-Project

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.

Q43Mini-ProjectMini-Project

Build a "Matrix Toolkit" using comprehensions: generate a 4x4 identity matrix, then transpose it, both via nested list comprehensions.

Q44Mini-ProjectMini-Project

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.

Q45Mini-ProjectMini-Project

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.

Q46InterviewInterview

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.

Q47InterviewInterview

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.

Q48InterviewInterview

Explain why list comprehensions are generally slightly faster than an equivalent for loop with .append(), and demonstrate measuring both with timeit.

Q49InterviewInterview

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.

Q50CapstoneInterview

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