0
0
Pythonprogramming~20 mins

List comprehension with condition 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 filtering even numbers
What is the output of this Python code?
nums = [1, 2, 3, 4, 5]
even_nums = [x for x in nums if x % 2 == 0]
print(even_nums)
Python
nums = [1, 2, 3, 4, 5]
even_nums = [x for x in nums if x % 2 == 0]
print(even_nums)
A[2, 4]
B[1, 3, 5]
C[1, 2, 3, 4, 5]
D[]
Attempts:
2 left
๐Ÿ’ก Hint
Remember, the condition filters only numbers divisible by 2.
โ“ Predict Output
intermediate
2:00remaining
List comprehension with else clause output
What is the output of this code?
nums = [1, 2, 3]
result = [x if x % 2 == 0 else 0 for x in nums]
print(result)
Python
nums = [1, 2, 3]
result = [x if x % 2 == 0 else 0 for x in nums]
print(result)
A[0, 2, 0]
B[1, 2, 3]
C[1, 0, 3]
D[2]
Attempts:
2 left
๐Ÿ’ก Hint
The else part replaces odd numbers with 0.
โ“ Predict Output
advanced
2:30remaining
Output of nested list comprehension with condition
What does this code print?
matrix = [[1, 2], [3, 4], [5, 6]]
result = [x for row in matrix for x in row if x % 2 == 0]
print(result)
Python
matrix = [[1, 2], [3, 4], [5, 6]]
result = [x for row in matrix for x in row if x % 2 == 0]
print(result)
A[1, 2, 3, 4, 5, 6]
B[1, 3, 5]
C[2, 4, 6]
D[2, 4]
Attempts:
2 left
๐Ÿ’ก Hint
It flattens the matrix and keeps only even numbers.
โ“ Predict Output
advanced
2:30remaining
Output of list comprehension with multiple conditions
What is printed by this code?
nums = range(10)
result = [x*x for x in nums if x % 2 == 0 and x > 5]
print(result)
Python
nums = range(10)
result = [x*x for x in nums if x % 2 == 0 and x > 5]
print(result)
A[25, 36, 49, 64, 81]
B[0, 4, 16, 36, 64]
C[6, 8]
D[36, 64]
Attempts:
2 left
๐Ÿ’ก Hint
Filter numbers that are even and greater than 5, then square them.
๐Ÿง  Conceptual
expert
3:00remaining
Understanding evaluation order in list comprehension with condition
Consider this code:
values = [0, 1, 2, 3]
result = [10 / x for x in values if x != 0]
print(result)

Which statement is true about this code?
AIt raises a ZeroDivisionError because 0 is in values.
BIt prints [10.0, 5.0, 3.3333333333333335] without error.
CIt prints [10, 5, 3] because division returns integers.
DIt raises a SyntaxError due to the condition placement.
Attempts:
2 left
๐Ÿ’ก Hint
The condition filters out zero before division happens.