0
0
Pythonprogramming~20 mins

List comprehension with if–else in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
List Comprehension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A[2, 4, 4, 8, 6]
B[2, 2, 4, 4, 6]
C[2, 4, 4, 8, 5]
D[1, 4, 3, 8, 5]
Attempts:
2 left
💡 Hint
Remember that the if–else inside the list comprehension applies to each element before adding it to the list.
Predict Output
intermediate
2: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]
A['even', 'even', 'even']
B['even', 'odd', 'even']
C['odd', 'odd', 'odd']
D['odd', 'even', 'odd']
Attempts:
2 left
💡 Hint
Check each number if it is divisible by 2.
Predict Output
advanced
2: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)
A[[5, 20], [8, 40]]
B[[6, 2], [8, 40]]
C[[6, 20], [8, 4]]
D[[6, 20], [8, 40]]
Attempts:
2 left
💡 Hint
Apply the if–else to each element inside each inner list.
🔧 Debug
advanced
2: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]
Aresult = [x*2 for x in nums if x > 1]
Bresult = [x*2 if x > 1 else x for x in nums]
Cresult = [x*2 if x > 1 for x in nums if x < 3]
Dresult = [x*2 if x > 1 else x for x in nums if x < 3]
Attempts:
2 left
💡 Hint
Check the placement of the if and else keywords in the comprehension.
🧠 Conceptual
expert
2: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?
AFor each x in data, cond(x) is checked first; then either f(x) or g(x) is called accordingly.
BAll f(x) are computed first, then all g(x) are computed after.
CThe functions f and g are called only once each before the comprehension starts.
Dcond(x) is checked after f(x) and g(x) are both called for each x.
Attempts:
2 left
💡 Hint
Think about how list comprehensions process each element one by one.