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.