0
0
Pythonprogramming~20 mins

Nested list comprehension in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Nested List Comprehension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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)
A[[0, 0, 0], [0, 1, 2], [0, 1, 2]]
B[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
C[[0, 0, 0], [1, 2, 3], [2, 4, 6]]
D[[0, 0, 0], [0, 1, 2], [0, 2, 4]]
Attempts:
2 left
๐Ÿ’ก Hint
Think about how the outer and inner loops multiply the indices.
โ“ Predict Output
intermediate
2: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)
A[[0, 2], [2, 4], [2, 4]]
B[[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]
C[[0, 2], [0, 2], [0, 2]]
D[[0, 2], [1, 3], [2, 4]]
Attempts:
2 left
๐Ÿ’ก Hint
Only include sums that are even numbers.
๐Ÿ”ง Debug
advanced
2: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])
ATypeError
BIndexError
CSyntaxError
DKeyError
Attempts:
2 left
๐Ÿ’ก Hint
Check the indices used to access the list elements.
๐Ÿ“ Syntax
advanced
2:00remaining
Which nested list comprehension is syntactically correct?
Choose the option that is a valid nested list comprehension in Python.
A[x + y for x in range(3), y in range(3)]
B[[x + y for x in range(3) if y] for y in range(3)]
C[[x + y for x in range(3)] for y in range(3)]
D[[x + y for x in range(3) for y in range(3)]]
Attempts:
2 left
๐Ÿ’ก Hint
Remember the syntax for nested list comprehensions uses separate for clauses inside brackets.
๐Ÿš€ Application
expert
3: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)?
A[[i * j for j in range(1, 6)] for i in range(1, 6)]
B[[i * j for i in range(1, 6)] for j in range(1, 6)]
C[[i + j for j in range(1, 6)] for i in range(1, 6)]
D[[i * j for j in range(5)] for i in range(5)]
Attempts:
2 left
๐Ÿ’ก Hint
Rows and columns start at 1, so use range(1, 6).