Recall & Review
beginner
What is list comprehension with condition in Python?
It is a way to create a new list by looping over an existing list and including only items that meet a certain condition.
Click to reveal answer
beginner
How do you write a list comprehension that includes only even numbers from a list
nums?Use:
This means: take each
[x for x in nums if x % 2 == 0] This means: take each
x in nums only if x is even.Click to reveal answer
beginner
What happens if the condition in a list comprehension is always false?
The result is an empty list because no items meet the condition to be included.
Click to reveal answer
intermediate
Can you use multiple conditions in a list comprehension? How?
Yes, by combining conditions with
and or or. Example: [x for x in nums if x > 0 and x % 2 == 0] selects positive even numbers.Click to reveal answer
beginner
Rewrite this code using list comprehension with condition:
result = []
for x in nums:
if x > 10:
result.append(x * 2)Using list comprehension:
[x * 2 for x in nums if x > 10]
Click to reveal answer
What does this list comprehension do?
[x for x in range(5) if x != 3]✗ Incorrect
It loops over numbers 0 to 4 and includes all except 3.
Which of these is a correct syntax for list comprehension with condition?
✗ Incorrect
The condition comes after the loop:
for x in nums if condition.What will be the output of
[x*2 for x in [1,2,3] if x > 2]?✗ Incorrect
Only 3 is greater than 2, so output is [3*2] = [6].
How can you filter out odd numbers from a list
nums using list comprehension?✗ Incorrect
Even numbers satisfy x % 2 == 0, so this keeps evens and filters out odds.
What does the condition part in list comprehension control?
✗ Incorrect
The condition decides if an item should be added to the new list.
Explain how to use list comprehension with a condition to create a list of squares of even numbers from another list.
Think about filtering first, then applying the square.
You got /3 concepts.
Describe what happens if the condition in a list comprehension never matches any item.
What does an empty filter mean for the output?
You got /3 concepts.