3
Lesson 3
Using multiple conditions
When you use multiple conditions in a list comprehension, it means you are adding extra rules about which items should go into the list.
Syntax:
Syntax:
[x for x in range(20) if x % 2 == 0 and x % 3 == 0]
Let’s dissect it:
x : This is each number as we loop throughrange(20) (numbers 0 to 19).if x % 2 == 0 : This checks ifx is divisible by 2 (no remainder), meaning it’s even.and x % 3 == 0 : This adds another condition:x must also be divisible by 3.- The whole thing: Only numbers that meet **both conditions** are added to the new list.
What’s Happening Here?
The goal is to create a list of numbers from 0 to 19 that satisfy two conditions:
1. The number is divisible by 2 (even number).
2. The number is divisible by 3.
Step-by-step walkthrough
Imagine you’re going through numbers 0 to 19 one by one:
1. For each number (
2. Then, check if it’s also divisible by 3.
3. If both conditions are true, add the number to the new list.
Example in action
Let’s work it out for
| Number | Divisible by 2? | Divisible by 3? | Added to List? |
|--------|------------------|------------------|----------------|
| 0 | Yes | Yes | ✅ |
| 1 | No | No | ❌ |
| 2 | Yes | No | ❌ |
| 3 | No | Yes | ❌ |
| 4 | Yes | No | ❌ |
| 5 | No | No | ❌ |
| 6 | Yes | Yes | ✅ |
| 7 | No | No | ❌ |
| 8 | Yes | No | ❌ |
| 9 | No | Yes | ❌ |
| 10 | Yes | No | ❌ |
| 11 | No | No | ❌ |
| 12 | Yes | Yes | ✅ |
| ... | ... | ... | ... |
The final list is:
[0, 6, 12, 18]
Why Use and ?
The
- If only one condition is true: The number is skipped.
- If both are true: The number is added.
Real-Life analogy
Imagine you’re picking players for a game. Your rules are:
1. The player must be taller than 180 cm.
2. The player must be younger than 25 years.
You only select players who meet both conditions. Anyone who doesn’t fit both is skipped.