Skip to content Skip to sidebar Skip to footer

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, number

Solution 1:

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

Solution 2:

Immediately solved this in the interpreter right after I posted.

forxin ( x forxin sublists if x ):

Not as clean as I'd like, the nested if statement is more readable in my opinion. I'm open to other suggestions if there is a cleaner way.

Solution 3:

I think you can't simplify the syntax to a one-liner in python, but indeed have to type out all the lines chaining for loops and if statements.

An exception to this are list comprehensions (see here at 5.1.3). They can be used to produce new lists from lists. An example:

test_list = ["Blue Candy", "Apple", "Red Candy", "Orange", "Pear", "Yellow Candy"]
candy_list = [x for x in test_list if "Candy" in x]

Post a Comment for "How Can I Combine A Conditional With A For Loop In Python?"