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

10,246

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.

for x in ( x for x in 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]
Share:
10,246

Related videos on Youtube

feyd
Author by

feyd

C# Developer professionally, and experience with a plethora of other languages/frameworks, too many to list.

Updated on September 15, 2022

Comments

  • feyd
    feyd over 1 year

    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.

    • matanster
      matanster over 3 years
      I believe python syntax does not afford any special concise form for that, other than the case that you only wish to create a new iterable. If you really want to loop more generally, you can choose your style from among the various options that come up in the answers or stick to your idiot-proof original style. No sugar for this ..
    • jonrsharpe
      jonrsharpe
      You could use filter or a list comprehension/generator expression, but it's probably not going to end up any shorter than the first version and likely less readable. Just use the first version.
  • feyd
    feyd over 5 years
    This is it, so clean! Think it print needs () though, I'll mark this as answer because this is exactly what I was looking for.
  • Radan
    Radan over 5 years
    Thank you, very happy I helped :) Cheers!
  • matanster
    matanster over 3 years
    Closest to the style the OP's was looking for, though probably not too legible for many people who would read this line very quickly. Less lines, but not really more concise than the original.