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 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)
Attempts:
2 left
๐ก Hint
Remember, the condition filters only numbers divisible by 2.
โ Incorrect
The list comprehension includes only numbers where x % 2 == 0, which are 2 and 4.
โ Predict Output
intermediate2: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)
Attempts:
2 left
๐ก Hint
The else part replaces odd numbers with 0.
โ Incorrect
For each number, if it is even, keep it; otherwise, replace with 0. So 1 and 3 become 0, 2 stays 2.
โ Predict Output
advanced2: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)
Attempts:
2 left
๐ก Hint
It flattens the matrix and keeps only even numbers.
โ Incorrect
The comprehension goes through each row, then each number, and keeps only even numbers: 2, 4, 6.
โ Predict Output
advanced2: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)
Attempts:
2 left
๐ก Hint
Filter numbers that are even and greater than 5, then square them.
โ Incorrect
Only 6 and 8 are even and greater than 5. Their squares are 36 and 64.
๐ง Conceptual
expert3:00remaining
Understanding evaluation order in list comprehension with condition
Consider this code:
Which statement is true about 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?
Attempts:
2 left
๐ก Hint
The condition filters out zero before division happens.
โ Incorrect
The condition x != 0 excludes zero, so division by zero never happens. Division returns floats.