0

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?

ApplePieGiraffe
  • 155
  • 1
  • 8
  • What's the `else` supposed to do…? – deceze Feb 06 '20 at 15:07
  • The second won't work because you can't have an `else` for the if at the end of the loop. That if means "insert the element in the final list *if* condition is true". The implicit else is "otherwise, skip this item". Don't mix up python's ternary operator with the insertion condition for comprehensions (even if they both look like if statements..) – GPhilo Feb 06 '20 at 15:08
  • @deceze It's not a duplicate since the OP asks for using a conditional for the nested iterable rather than the loop expression. Technically it's similar but concept-wise a bit different. – a_guest Feb 06 '20 at 15:41
  • 1
    @a_guest Without clarification of what that `if..else` is supposed to do exactly (which is unclear to me from the given information), pointing to that dupe is the only sensible thing I can think of. – deceze Feb 06 '20 at 16:20
  • @deceze Since the OP already includes the duplicate's answer (`[ if else for in `) this is apparently not what they are looking for. In case the question is unclear it should be closed and asking for clarity. – a_guest Feb 07 '20 at 07:31

0 Answers0