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.
In this tutorial, we will learn how to apply multiple if conditions in List Comprehension.
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.
Example 1: List Comprehension using IF Condition
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.
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.
[6, 15, 3, 9]
Example 2: List Comprehension using Multiple IF Conditions and Multiple Input Lists
In this example, we shall create a new list from two lists of numbers with given multiple if conditionals.
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)
[4, 6, 8, 8, 12, 16, 12, 18, 24]
In this tutorial of Python Examples, we learned how to use List Comprehension with Multiple Conditions in it.