Search code examples
pythonpython-3.xlistif-statementlogical-and

How can I filter a list by different conditions?


I've written the following code:

list_1 = [5, 18, 3]
list_2 = []
for element in list_1:
    if element < 0:
        list_2.append(element)
    elif element % 9 == 0:
        list_2.append(element)
    elif element % 2 != 0: 
        list_2.append(element)
    else:
        print('No number is valid')
print(list_2)

The problem is that this returns a list of numbers that satisfy at least one of the 3 conditions.

The result I want is a list of the numbers that satisfy all three conditions. How could I achieve that?


Solution

  • Try list comprehension :

    list_2 = [i for i in list_1 if i<0 and i%9==0 and i%2 !=0]