Python List Comprehension with Multiple IF Conditions


Python List Comprehension - Multiple If Conditions

Python List Comprehension is used to create Lists. While generating elements of this list, you can provide conditions that could be applied whether to include this element in the list.

In our previous tutorial, we learned how to include an if condition in list comprehension.

Python List Comprehension with Single If Condition

In this tutorial, we will learn how to apply multiple if conditions in List Comprehension.

Syntax

Following is the syntax of List Comprehension with IF Condition.

output = [ expression for element in list_1 if condition_1 if condition_2 ]

where condition is applied, and the element (evaluation of expression) is included in the output list, only if the condition_1 evaluates to True and condition_2 evaluates to True.

Examples

1. List Comprehension using two If conditions

In this example, we shall create a new list from a list of integers, only for those elements in the input list that satisfy given conditions.

Python Program

list_1 = [7, 2, -8, 6, 2, 15, 4, -2, 3, 9]
list_2 = [ x for x in list_1 if x > 0 if x % 3 == 0 ]
print(list_2)

We have taken a list of integers. Then using list comprehension, we are creating a list containing elements of the input list, but with conditions that the element is greater than zero and the element is exactly divisible by 3.

Output

[6, 15, 3, 9]

2. List Comprehension with two If conditions and two input lists

In this example, we shall create a new list from two lists of numbers with given multiple if conditionals.

Python Program

list_1 = [-2, -1, 0, 1, 2, 3]
list_2 = [4, 5, 6, 7, 8]
list_3 = [ x * y for x in list_1 for y in list_2 if x > 0 if y % 2 == 0 ]
print(list_3)

Output

[4, 6, 8, 8, 12, 16, 12, 18, 24]

Summary

In this tutorial of Python Examples, we learned how to use List Comprehension with Multiple Conditions in it.