Recall & Review
beginner
What is list comprehension with if–else in Python?
It is a way to create a new list by applying a condition to each item, choosing one value if the condition is true and another if false, all in one line.
Click to reveal answer
beginner
How do you write a list comprehension with if–else?
Use the syntax: [ if <condition> else for <item> in <iterable>].
Click to reveal answer
beginner
Example: What does this code do? [x*2 if x > 5 else x+2 for x in range(8)]
It creates a list where numbers greater than 5 are doubled, and numbers 5 or less have 2 added. Result: [2, 3, 4, 5, 6, 7, 12, 14]
Click to reveal answer
intermediate
Can you use if–else inside list comprehension without an else part?
No, if you want to choose between two values, you must include else. But you can filter items with if alone (no else) to include only some items.
Click to reveal answer
beginner
Why use list comprehension with if–else instead of a for loop?
It makes code shorter and easier to read by combining looping and conditional logic in one line.
Click to reveal answer
What is the correct syntax for list comprehension with if–else?
✗ Incorrect
The correct syntax places the if–else expression before the for loop: [value_if_true if condition else value_if_false for item in iterable].
What will this list comprehension produce? [x+1 if x % 2 == 0 else x-1 for x in range(4)]
✗ Incorrect
For even numbers (0,2), add 1 → 1,3; for odd numbers (1,3), subtract 1 → 0,2; final list: [1,0,3,2].
Can you omit the else part in a list comprehension with if–else?
✗ Incorrect
When using if–else in list comprehension, else is required to handle the false case.
Which of these is a valid use of if in list comprehension without else?
✗ Incorrect
You can filter items with if alone: [x for x in range(5) if x > 2] includes only items greater than 2.
Why might you choose list comprehension with if–else over a for loop?
✗ Incorrect
List comprehension with if–else combines looping and condition in one line, making code shorter and easier to read.
Explain how to use if–else inside a list comprehension and give a simple example.
Think about how you pick one value if true and another if false for each item.
You got /3 concepts.
Describe the difference between using if alone and if–else in list comprehensions.
Consider when you want to include or exclude items versus when you want to transform items differently.
You got /3 concepts.