Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine a conditional with a for loop in Python?

I have a simple example I've drawn up. I thought it was possible to combine if statements and for loops with minimal effort in Python. Given:

sublists = [number1, number2, number3]

for sublist in sublists:
    if sublist:
        print(sublist)

I thought I could condense the for loop to:

for sublist in sublists if sublist:

but this results in invalid syntax. I'm not too particular on this example, I just want a method of one lining simple if statements with loops.

like image 814
feyd Avatar asked Dec 13 '22 15:12

feyd


1 Answers

if you want to filter out all the empty sub list from your original sub lists, you will have to do something like below. this will give you all the non empty sub list.

print([sublist for sublist in sublists if sublist])

*edited for syntax

like image 104
Radan Avatar answered Mar 24 '23 22:03

Radan