Python List Comprehension – IF Condition
Python List Comprehension is used to create Lists. While generating elements of this list, you can provide condition that could be applied on the input lists to list comprehension.
In this tutorial, we will learn how to apply an if condition on input list(s) in List Comprehension.
Following is the syntax of List Comprehension with IF Condition.
output = [ expression for element in list_1 if condition ]
where condition is applied, and the element (evaluation of expression) is included in the output list, only if the condition 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 a given condition.
list_1 = [7, 2, 6, 2, 5, 4, 3] list_2 = [ x * x for x in list_1 if (x % 2 == 0) ] print(list_2)
We have taken a list of integers. Then using list comprehension, we are generating a list containing squares of the elements in the input list, but with a condition that only if the element in input list is even number.
[4, 36, 4, 16]
Example 2: List Comprehension using IF Condition and Multiple Input Lists
In this example, we shall create a new list from two lists of integers with a given condition.
list_1 = [1, 2, 3] list_2 = [4, 5, 6] list_3 = [ x * y for x in list_1 for y in list_2 if (x+y)%2 == 0 ] print(list_3)
[5, 8, 12, 15]
In this tutorial of Python Examples, we learned how to use List Comprehension with an IF Condition in it.