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)
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 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.