You are putting the else in the for
clause of the comprehension, but you need to put the entire if/else expression in the target expression:
[tower if tower != space else [] for tower in state]
When you use for tower in state if
you are saying you want to not even make use of items in state
if they don't satisfy the condition. In this case, you can't use an else
, because all you can do is either process each item (including something in the list comprehension result), or not.
The X if Y else Z
, on the other hand, is a normal expression that can be used as the target expression of the list comprehension. This means that every element in the source iterable will generate an element in the result, but the if/else determines what that result item will be.