Bird
Raised Fist0
Pythonprogramming~10 mins

List comprehension with if–else in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - List comprehension with if–else
Start with input list
For each item in list
Check condition?
Apply if-part
Add result to new list
Repeat for all items
Return new list
We go through each item in the list, check a condition, then choose a value based on if the condition is true or false, building a new list.
Execution Sample
Python
numbers = [1, 2, 3, 4]
result = [x*2 if x % 2 == 0 else x+1 for x in numbers]
print(result)
This code doubles even numbers and adds 1 to odd numbers in the list.
Execution Table
Stepx (current item)Condition (x % 2 == 0)ActionResult added to listList so far
11Falsex+12[2]
22Truex*24[2, 4]
33Falsex+14[2, 4, 4]
44Truex*28[2, 4, 4, 8]
💡 All items processed, list comprehension ends with final list.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
x-1234-
result[][2][2, 4][2, 4, 4][2, 4, 4, 8][2, 4, 4, 8]
Key Moments - 3 Insights
Why do we write the if–else before the for loop in the comprehension?
In list comprehension with if–else, the if–else expression comes before the for loop because it decides the value to add for each item. The execution_table rows show the condition and action happen for each x before moving to the next.
What happens if the condition is true or false?
If the condition is true, the 'if' part runs (like x*2). If false, the 'else' part runs (like x+1). The execution_table shows this clearly in the 'Action' and 'Result added' columns.
Is this the same as filtering items?
No. This if–else chooses what value to add for every item. Filtering would skip items. Here, every item produces a result, as seen in every step of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'result' after step 3?
A[2, 4, 3]
B[2, 4, 4]
C[1, 2, 3]
D[2, 4, 6]
💡 Hint
Check the 'List so far' column in row 3 of the execution_table.
At which step does the condition 'x % 2 == 0' become True for the first time?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Condition' column in the execution_table rows.
If we change the condition to 'x > 2', what would be the result added at step 2?
A1
B4
C3
D5
💡 Hint
Step 2 has x=2; check if 2 > 2 is True or False and what action applies.
Concept Snapshot
List comprehension with if–else syntax:
[result_if_true if condition else result_if_false for item in iterable]

- Checks condition for each item
- Chooses one of two results
- Builds new list with all results

Useful for transforming lists with choices.
Full Transcript
This lesson shows how list comprehension with if–else works in Python. We start with a list of numbers. For each number, we check if it is even. If yes, we double it. If no, we add one. We add the result to a new list. This repeats for all items. The final list contains transformed values based on the condition. The execution table tracks each step, showing the current item, condition result, action taken, and the list building up. Key points include the placement of if–else before the for loop, how both true and false cases produce results, and that this is not filtering but transforming every item. The quiz checks understanding of the list state at steps, condition truth, and effect of changing the condition.

Practice

(1/5)
1. What does the following list comprehension do?
[x if x % 2 == 0 else -x for x in range(5)]
easy
A. Creates a list of numbers from 0 to 4 without changes
B. Creates a list of numbers where even numbers stay the same and odd numbers become negative
C. Creates a list of only negative numbers from 0 to 4
D. Creates a list of only even numbers from 0 to 4

Solution

  1. Step 1: Understand the condition in the comprehension

    The condition x % 2 == 0 checks if a number is even.
  2. Step 2: Apply the if-else for each number in range(5)

    If even, keep x; if odd, use -x. So 0,2,4 stay same; 1,3 become -1,-3.
  3. Final Answer:

    Creates a list of numbers where even numbers stay the same and odd numbers become negative -> Option B
  4. Quick Check:

    if-else picks value based on even check = D [OK]
Hint: If-else picks value before for loop [OK]
Common Mistakes:
  • Thinking if-else goes after the for loop
  • Confusing condition meaning (odd vs even)
  • Ignoring the else part
2. Which of these is the correct syntax for a list comprehension with if-else in Python?
easy
A. [x if x > 0 else 0 for x in nums]
B. [x for x in nums if x > 0 else 0]
C. [if x > 0 then x else 0 for x in nums]
D. [x if x > 0 else 0 in nums]

Solution

  1. Step 1: Recall correct if-else placement in list comprehension

    The if-else expression must come before the for loop inside the brackets.
  2. Step 2: Check each option's syntax

    [x if x > 0 else 0 for x in nums] correctly places x if x > 0 else 0 before for x in nums. Others have syntax errors.
  3. Final Answer:

    [x if x > 0 else 0 for x in nums] -> Option A
  4. Quick Check:

    if-else before for loop = C [OK]
Hint: If-else must be before for in comprehension [OK]
Common Mistakes:
  • Putting if-else after the for loop
  • Using 'then' keyword (not in Python)
  • Missing for loop entirely
3. What is the output of this code?
nums = [1, 2, 3, 4]
result = [x*2 if x % 2 == 0 else x+1 for x in nums]
print(result)
medium
A. [2, 4, 4, 6]
B. [2, 4, 4, 4]
C. [2, 4, 4, 8]
D. [2, 2, 4, 8]

Solution

  1. 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.
  2. Step 2: Collect results in list

    The final list is [2, 4, 4, 6].
  3. Final Answer:

    [2, 4, 4, 6] -> Option A
  4. Quick Check:

    if even *2 else +1 = [2,4,4,6] [OK]
Hint: Check each item with condition carefully [OK]
Common Mistakes:
  • Mixing up multiplication and addition
  • Applying condition after the loop
  • Wrong output list length
4. Find the error in this list comprehension:
values = [10, 15, 20]
new_values = [x if x > 15 else x*2 for x in values if x]
medium
A. The if condition after the for loop is invalid syntax
B. The if-else expression must be inside parentheses
C. No error, code runs fine
D. The else part should come after the for loop

Solution

  1. Step 1: Analyze the list comprehension structure

    The if-else expression is before the for loop, and the trailing if filters values.
  2. Step 2: Confirm syntax correctness

    Trailing if after for is allowed to filter items; no syntax error here.
  3. Final Answer:

    No error, code runs fine -> Option C
  4. Quick Check:

    Trailing if filters allowed = B [OK]
Hint: Trailing if filters items, allowed after for [OK]
Common Mistakes:
  • Thinking trailing if is invalid
  • Expecting else after for loop
  • Misplacing parentheses
5. You have a list of temperatures in Celsius: 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?
hard
A. [temp for temp in temps if temp >= 0 else 'Freezing']
B. [temp if temp < 0 else 'Freezing' for temp in temps]
C. [temp if temp > 0 else 'Freezing' for temp in temps]
D. ['Freezing' if temp < 0 else temp for temp in temps]

Solution

  1. Step 1: Understand the condition and output

    Temperatures below 0 become 'Freezing', others stay numbers.
  2. 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 temp before the for loop. Others have wrong order or logic.
  3. Final Answer:

    ['Freezing' if temp < 0 else temp for temp in temps] -> Option D
  4. Quick Check:

    if-else before for, correct condition = A [OK]
Hint: Put if-else before for, condition matches output [OK]
Common Mistakes:
  • Swapping if and else parts
  • Placing if-else after for loop
  • Using filter if instead of if-else expression