Python List Comprehension containing IF Condition

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.

Syntax

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.

Examples

1. Filter only even numbers using List Comprehension

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.

Python Program

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)
Run Code Copy

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.

Output

[4, 36, 4, 16]

2. List Comprehension using If condition on multiple input lists

In this example, we shall create a new list from two lists of integers with a given condition.

Python Program

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)
Run Code Copy

Output

[5, 8, 12, 15]

Summary

In this tutorial of Python Examples, we learned how to use List Comprehension with an IF Condition in it.

Related Tutorials

Code copied to clipboard successfully 👍