I'm trying to use an if... else
conditional for the inner loop in of a nested list comprehension in Python, but I keep on getting syntax errors.
This seems to work fine:
[<expression> for <variable> in <iterable> for <nested_variable> in <variable> if <expression>]
And I know this won't work:
[<expression> for <variable> in <iterable> for <nested_variable> in <variable> if <expression> else <expression>]
And that's because an if... else
statement in a list comprehension must be placed before the actual loop, as in:
[<expression> if <expression> else <expression> for <variable> in <iterable>
But when I try to do the above for the nested loop in my nested list comprehension, I keep getting syntax errors:
[<expression> for <variable> in <iterable> if <expression> else <expression> for <nested_variable> in <variable>]
I've tried using parentheses to group my loops or something, but I just run into more syntax errors.
Is it possible to use an if... else
conditional for the nested loop in a nested list comprehension in Python?
If so, how?