Challenge - 5 Problems
Nested List Comprehension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of nested list comprehension with condition
What is the output of the following Python code?
Python
result = [[x * y for y in range(3)] for x in range(3)] print(result)
Attempts:
2 left
๐ก Hint
Think about how the outer and inner loops multiply the indices.
โ Incorrect
The outer loop runs x from 0 to 2. The inner loop runs y from 0 to 2. Each element is x*y, so for x=0 all are 0, for x=1 it's [0,1,2], for x=2 it's [0,2,4].
โ Predict Output
intermediate2:00remaining
Nested list comprehension with filtering
What is the output of this code snippet?
Python
result = [[x + y for y in range(4) if (x + y) % 2 == 0] for x in range(3)] print(result)
Attempts:
2 left
๐ก Hint
Only include sums that are even numbers.
โ Incorrect
For each x from 0 to 2, include x+y only if (x+y) even: x=0: y=0(0), y=2(2) โ [0,2]; x=1: y=1(2), y=3(4) โ [2,4]; x=2: y=0(2), y=2(4) โ [2,4].
๐ง Debug
advanced2:00remaining
Identify the error in nested list comprehension
What error does this code raise when run?
Python
result = [[x * y for x in range(3)] for y in range(3)] print(result[3][0])
Attempts:
2 left
๐ก Hint
Check the indices used to access the list elements.
โ Incorrect
The outer list has 3 elements indexed 0,1,2. Accessing index 3 causes IndexError.
๐ Syntax
advanced2:00remaining
Which nested list comprehension is syntactically correct?
Choose the option that is a valid nested list comprehension in Python.
Attempts:
2 left
๐ก Hint
Remember the syntax for nested list comprehensions uses separate for clauses inside brackets.
โ Incorrect
Option C has invalid syntax with comma between for clauses. Option C uses correct nested list comprehension syntax for a 2D list. Option C is syntactically valid but adds a filter. Option C uses chained for clauses in one comprehension, creating a list with a single flat sublist.
๐ Application
expert3:00remaining
Create a multiplication table using nested list comprehension
Which option creates a 5x5 multiplication table (list of lists) where each element is the product of its row and column indices (starting from 1)?
Attempts:
2 left
๐ก Hint
Rows and columns start at 1, so use range(1, 6).
โ Incorrect
Option A correctly multiplies row index i and column index j from 1 to 5. Option A produces the same table due to commutativity of multiplication. Option A adds instead of multiplies. Option A starts indices from 0.