Challenge - 5 Problems
List Comprehension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of list comprehension with if–else
What is the output of the following Python code?
Python
numbers = [1, 2, 3, 4, 5] result = [x*2 if x % 2 == 0 else x+1 for x in numbers] print(result)
Attempts:
2 left
💡 Hint
Remember that the if–else inside the list comprehension applies to each element before adding it to the list.
✗ Incorrect
For each number, if it is even (x % 2 == 0), multiply by 2; otherwise, add 1. So 1+1=2, 2*2=4, 3+1=4, 4*2=8, 5+1=6.
❓ Predict Output
intermediate2:00remaining
Value of variable after list comprehension
What is the value of
output after running this code?Python
values = [10, 15, 20] output = ['even' if v % 2 == 0 else 'odd' for v in values]
Attempts:
2 left
💡 Hint
Check each number if it is divisible by 2.
✗ Incorrect
10 is even, 15 is odd, 20 is even, so the list is ['even', 'odd', 'even'].
❓ Predict Output
advanced2:00remaining
Output of nested list comprehension with if–else
What is the output of this nested list comprehension?
Python
matrix = [[1, 2], [3, 4]] result = [[x*10 if x % 2 == 0 else x+5 for x in row] for row in matrix] print(result)
Attempts:
2 left
💡 Hint
Apply the if–else to each element inside each inner list.
✗ Incorrect
For each number: if even, multiply by 10; if odd, add 5. So 1+5=6, 2*10=20, 3+5=8, 4*10=40.
🔧 Debug
advanced2:00remaining
Identify the error in list comprehension with if–else
Which option will cause a SyntaxError when running this code?
Python
nums = [1, 2, 3] result = [x*2 if x > 1 for x in nums]
Attempts:
2 left
💡 Hint
Check the placement of the if and else keywords in the comprehension.
✗ Incorrect
Option C has two 'if' clauses without an 'else' in the ternary expression, causing SyntaxError.
🧠 Conceptual
expert2:00remaining
Understanding evaluation order in list comprehension with if–else
Consider this code snippet:
result = [f(x) if cond(x) else g(x) for x in data]Which statement best describes the evaluation order?
Attempts:
2 left
💡 Hint
Think about how list comprehensions process each element one by one.
✗ Incorrect
The condition cond(x) is evaluated for each element x; based on that, either f(x) or g(x) is called immediately.