List comprehensions support if
but not else
because the if
section filters elements, you either include an element or you don't include it, a boolean choice.
If you wanted to use a conditional expression to build the iterable part of the for
loop, use parentheses:
return [tower for tower in (state if tower != space else [])]
but I suspect that you wanted to alter the value of the expression in the element expression instead; that's not filtering, you are simply producing a different value for certain items. Use a conditional expression to produce your values:
return [tower if tower != space else [] for tower in state]
or if you really wanted to filter, simply omit the else
:
return [tower for tower in state if tower != space]
When constructing a list comprehension, remember that you need to read the expression as nested from left to right, with the final expression producing the result out on the left:
[element_producing_expression for name in iterable if filter_expression]
is the moral equivalent of:
for name in iterable:
if filter_expression:
element_producing_expression
where you can use as many nested loops and if
filters as your use case requires.
The three options I described above are then the same as:
# conditional expression producing the iterable
for tower in (state if tower != space else []):
tower
# conditional expression in the element expression
for tower in state:
tower if tower != space else []
# filtering expression with no else
for tower in state:
if tower != space:
tower