Skip to content

Python list comprehension multiple conditions | Example code

  • by

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]
print(list_3)

Output:

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]

print(res)

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

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading