Search code examples
pythonfor-loopif-statementlist-comprehension

If and else inside a one-line python loop


Sorry if being so simple; as I searched elsewhere but nobody had pointed out to this specific problem. I'd like to learn python in a way that makes my code compact! So, to this end, I'm trying to make use of one-line (i.e., short) loops instead of multi-line loops, specifically, for loops. The problem arises when I try to use one-line if and else inside the one-line loops. It just doesn't seem to be working. Consider the following, for example:

numbers = ... # an arbitrary array of integer numbers

over_30 = [number if number > 30 for number in numbers]

This is problematic since one-line if does need else following it. Even though, when I add else to the above script (after if): over_30 = [number if number > 30 else continue for number in numbers], it turns into just another pythonic error.

I know that the problem is actually with one-line if and else, because python needs to identify a value that should be assigned to the lefthand operator. But, is there a work-around for the specific use-case of this schema as above?


Solution

  • They are different syntaxes. The one you are looking for is:

    over_30 = [number for number in numbers if number > 30]
    

    This is a conditional list comprehension. The else clause is actually a non-conditional list comprehension, combined with a ternary expression:

    over_30 = [number if number > 30 else 0 for number in numbers]
    

    Here you are computing the ternary expression (number if number > 30 else 0) for each number in the numbers iterable.