List comprehension with if-else lets you create a new list by choosing values based on a condition, all in one simple line.
List comprehension with if–else in Python
Start learning this pattern below
Jump into concepts and practice - no test required
new_list = [value_if_true if condition else value_if_false for item in original_list]
The if-else part goes before the for loop in the list comprehension.
This is different from a simple if filter, which comes after the for loop.
numbers = [1, 2, 3, 4] labels = ['even' if num % 2 == 0 else 'odd' for num in numbers] print(labels)
temps = [-5, 3, 0, -1] non_negative = [temp if temp >= 0 else 0 for temp in temps] print(non_negative)
scores = [55, 70, 40] results = ['pass' if score >= 50 else 'fail' for score in scores] print(results)
prices = [100, 250, 50] discounted = [price * 0.9 if price > 100 else price for price in prices] print(discounted)
This program labels each number in the list as 'even' or 'odd' using list comprehension with if-else.
def label_numbers(numbers): print(f"Original numbers: {numbers}") labeled = ['even' if number % 2 == 0 else 'odd' for number in numbers] print(f"Labeled numbers: {labeled}") numbers_list = [10, 15, 22, 33, 40] label_numbers(numbers_list)
Time complexity is O(n) because it processes each item once.
Space complexity is O(n) since it creates a new list of the same size.
A common mistake is putting the if-else after the for loop, which causes syntax errors.
Use this when you want to choose between two values for each item. Use a simple if filter if you want to include or exclude items.
List comprehension with if-else lets you pick one of two values for each item based on a condition.
The if-else goes before the for loop inside the brackets.
This makes your code shorter and easier to read when transforming lists.
Practice
[x if x % 2 == 0 else -x for x in range(5)]Solution
Step 1: Understand the condition in the comprehension
The conditionx % 2 == 0checks if a number is even.Step 2: Apply the if-else for each number in range(5)
If even, keepx; if odd, use-x. So 0,2,4 stay same; 1,3 become -1,-3.Final Answer:
Creates a list of numbers where even numbers stay the same and odd numbers become negative -> Option BQuick Check:
if-else picks value based on even check = D [OK]
- Thinking if-else goes after the for loop
- Confusing condition meaning (odd vs even)
- Ignoring the else part
Solution
Step 1: Recall correct if-else placement in list comprehension
The if-else expression must come before the for loop inside the brackets.Step 2: Check each option's syntax
[x if x > 0 else 0 for x in nums] correctly placesx if x > 0 else 0beforefor x in nums. Others have syntax errors.Final Answer:
[x if x > 0 else 0 for x in nums] -> Option AQuick Check:
if-else before for loop = C [OK]
- Putting if-else after the for loop
- Using 'then' keyword (not in Python)
- Missing for loop entirely
nums = [1, 2, 3, 4] result = [x*2 if x % 2 == 0 else x+1 for x in nums] print(result)
Solution
Step 1: Evaluate each element with condition
For each number: if even, multiply by 2; if odd, add 1. So 1->2, 2->4, 3->4, 4->8.Step 2: Collect results in list
The final list is [2, 4, 4, 6].Final Answer:
[2, 4, 4, 6] -> Option AQuick Check:
if even *2 else +1 = [2,4,4,6] [OK]
- Mixing up multiplication and addition
- Applying condition after the loop
- Wrong output list length
values = [10, 15, 20] new_values = [x if x > 15 else x*2 for x in values if x]
Solution
Step 1: Analyze the list comprehension structure
The if-else expression is before the for loop, and the trailing if filters values.Step 2: Confirm syntax correctness
Trailing if after for is allowed to filter items; no syntax error here.Final Answer:
No error, code runs fine -> Option CQuick Check:
Trailing if filters allowed = B [OK]
- Thinking trailing if is invalid
- Expecting else after for loop
- Misplacing parentheses
temps = [22, -5, 0, 15, -10]. Use a list comprehension with if-else to create a new list where temperatures below 0 become the string 'Freezing', and others stay as numbers.Which code does this correctly?
Solution
Step 1: Understand the condition and output
Temperatures below 0 become 'Freezing', others stay numbers.Step 2: Check each option's if-else placement and logic
['Freezing' if temp < 0 else temp for temp in temps] correctly uses'Freezing' if temp < 0 else tempbefore the for loop. Others have wrong order or logic.Final Answer:
['Freezing' if temp < 0 else temp for temp in temps] -> Option DQuick Check:
if-else before for, correct condition = A [OK]
- Swapping if and else parts
- Placing if-else after for loop
- Using filter if instead of if-else expression
