Blog Post #121: Adding Logic to Comprehensions with if Clauses

In Post #120, we were introduced to the power of list comprehensions for creating a new list by applying an expression to every item in an existing one, like [x**2 for x in numbers].

But what if we don’t want to include every item? What if we only want to apply the expression to items that meet a certain condition?

This is where the optional if clause in a list comprehension comes in. In this post, we’ll learn how to add a filter to our comprehensions to make them even more powerful.

The for Loop with a Filter

Let’s start with a familiar pattern. If we wanted to create a new list containing only the even numbers from an existing list, we would write a for loop with an if statement inside it.

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even_numbers = []

for number in numbers:
    # Check if the number meets our condition
    if number % 2 == 0:
        # If it does, add it to the new list
        even_numbers.append(number)

print(even_numbers)

This is a filtering pattern: we iterate through all the items but only append the ones that pass a certain test.

Adding an if Clause to a Comprehension

A list comprehension can handle this filtering pattern by adding an if clause to the very end.

The syntax is:

new_list = [expression for item in iterable if condition]

The logic is simple: The if condition part is evaluated for every item. The expression is only applied and its result added to the new list for those items where the condition evaluates to True.

You can read it like: “Give me the expression for each item in the iterable if the condition is met.

Filtering in Action

Let’s rewrite our even number example using this new, concise syntax.

numbers = [1, 2, 3, 4, 5, 6, 7, 8]

# The 'if' clause at the end acts as a filter
even_numbers = [number for number in numbers if number % 2 == 0]

print(even_numbers)

The output is the same: [2, 4, 6, 8]. The if number % 2 == 0 acts as a gate, only allowing the even numbers through to be included in the final list.

Combining Transformation and Filtering

The real power of comprehensions is that you can transform and filter at the same time. The expression (the ‘what to do’ part) and the condition (the ‘which ones to include’ part) are separate.

Let’s create a list of the squares of only the odd numbers from a list.

numbers = [1, 2, 3, 4, 5, 6]

# The expression is 'number ** 2'
# The condition is 'if number % 2 != 0'
odd_squares = [number ** 2 for number in numbers if number % 2 != 0]

print(odd_squares)

Here, the for loop iterates through all the numbers. The if clause filters out the even ones. Only for the remaining odd numbers (1, 3, 5) is the expression part (number ** 2) executed. The final output is: [1, 9, 25].

What’s Next?

You’ve now leveled up your list comprehension skills! By adding an if clause at the end, you can create new lists that are not only transformed but also filtered from a source iterable, all in one concise and readable line.

The if clause we just learned is a filter—it decides whether or not to include an item. But what if we want to apply a different expression based on a condition? For example, ‘label the number as “even” if it’s even, or “odd” if it’s odd’. For this, we need an if-else structure, and it goes in a different place in the comprehension. In Post #122, we will explore how to use a ternary operator to perform if-else logic inside a list comprehension.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment