Learning by doing. Practice this lesson with coding exercices.
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 as range()).
2. You want to pick only the items that meet a specific condition.
3. The condition is written after the if in the list comprehension.

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 in range(10) (from 0 to 9).
  • if x % 2 == 0: Only include x in the new list if x 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: ["apple", "banana", "cherry"]. You only want the words that are longer than 5 letters.

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 include word if its length is greater than 5.

Key Points


1. The condition (after the if) decides what gets included in the new list.
2. You don’t need to write a full loop and append—list comprehensions handle it all!
3. The result is a new list with only the items that passed the condition.
Learning by doing. Practice this lesson with coding exercices.
2
You've Completed Lesson 2

Next Up

3: Using multiple conditions

Learn how to use multiple conditions in Python list comprehension to filter data based on multiple rules, with examples like numbers divisible by 2 and 3.

Start Lesson 3