2
Lesson 2
Filtering with conditions in list comprehensions
A list comprehension lets you create a new list from an existing one, and you can add a condition to control what gets included in the new list.
Here’s the basic idea:
1. You have a list (or something like it, such asrange() ).
2. You want to pick only the items that meet a specific condition.
3. The condition is written after theif in the list comprehension.
Let’s say you want a list of even numbers from 0 to 9.
Without list comprehension, you might write this:
Here’s the basic idea:
1. You have a list (or something like it, such as
2. You want to pick only the items that meet a specific condition.
3. The condition is written after the
Example 1: Even Numbers
Let’s say you want a list of even numbers from 0 to 9.
Without list comprehension, you might write this:
even_numbers = [] for x in range(10): # Go through numbers 0 to 9 if x % 2 == 0: # Check if the number is even even_numbers.append(x) # Add it to the list if it is print(even_numbers) # Output: [0, 2, 4, 6, 8]
But with a list comprehension, you can do the same thing in one line:
even_numbers = [x for x in range(10) if x % 2 == 0] print(even_numbers) # Output: [0, 2, 4, 6, 8]
Here’s what’s happening:
x : Each number inrange(10) (from 0 to 9).if x % 2 == 0 : Only includex in the new list ifx is divisible by 2 (this is how you check for even numbers).
Example 2: Long words
Now let’s say you have a list of words:
Without list comprehension:
long_words = [] for word in ["apple", "banana", "cherry"]: if len(word) > 5: # Check if the word is longer than 5 letters long_words.append(word) # Add it to the list if it is print(long_words) # Output: ['banana', 'cherry']
With list comprehension:
long_words = [word for word in ["apple", "banana", "cherry"] if len(word) > 5] print(long_words) # Output: ['banana', 'cherry']
Here’s what’s happening:
word : Each word in the list["apple", "banana", "cherry"] .if len(word) > 5 **: Only includeword if its length is greater than 5.
Key Points
1. The condition (after the
2. You don’t need to write a full loop and
3. The result is a new list with only the items that passed the condition.