Python list comprehension multiple conditions | Example code

You can generate a new list by using list comprehension multiple conditions in Python. Multiple conditions are applied whether to include this element in the new list.

Multiple IF Conditions syntax

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

Python example list comprehension multiple conditions

Simple example code creates a new list from two lists with given 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]


Python list comprehension multiple conditions

Another Example

Using for loop, range function and in with multiple if conditions in a list comprehension

res = [i for i in range(100) if i % 10 == 0 if i < 50]


Output: [0, 10, 20, 30, 40]

Do comment if you have any doubts and suggestions on this Python list tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.