Search code examples
pythonpython-2.7if-statementconditional-expressions

Is there a way to execute two statements based on <condition> in one line?


Is it possible to write a one line like this: <statement> if <cond> else <statement>. I don't mean something like a = 1 if 1 else 2.

Example:

I have a list p that in itself has lists. Let's assume I get an input inputIter. I would like to do the following:

for input in inputIter:
    if <condition>: p+=[[input]] # generate new list
    else: p[-1]+=[input] # append to latest list

Then I thought to myself that there has to be a way to make this a one-liner so I tried this:

for input in inputIter:
    p+=[[input]] if <condition> else p[-1]+=[input]

But this generates

Syntax error: invalid syntax               ^

(where the = is at). Is there a workaround? I know this may not be the best example. I know it may look a bit ugly. But in my opinion it is readable.


Solution

  • You cannot mix statements into assignments, no.

    Assignment is a statement (=, +=, etc.). An assignment statement contains an expression (everything to the right of the =), but it cannot itself be used inside of an expression. There are specific reason for this: assignments in expression lead to hard-to-find bugs. The classical example is confusing equality testing (==) with assignment:

    if x = 0:
        # oops, that wasn't a test..
    

    See the Python FAQ.

    You are trying to switch between assignments within a conditional expression, and that's not allowed in Python.

    Just use if statements; in your specific example you could perhaps use:

    for input in inputIter:
        if <condition>: 
            p.append([]) # generate new list
        p[-1].append(input)
    

    This always appends to the last nested list, but when <condition> is a new, empty list is added at the end first.