List comprehension in Python : if else not working

Advertisements

I’m trying to add number of False in a list equivalent to a variable number, working if the variable is not 0. I’m trying to add a "else" statement if the variable is 0 but it’s not working.

Here is what I tired :

floors = 5

blocked_floor = [False for i in range(floors) if (floors > 0) else False]
blocked_floor1 = [False for i in range(floors) if (floors > 0) else False for i in range(1)]

There are a lot of topics about that issue but I tried everything that was in, nothing worked. I have a synthax error on the "else".

Do you have any idea about the issue ?

>Solution :

Your syntax is indeed wrong.

Instead of:

blocked_floor1 = [False for i in range(floors) if (floors > 0) else False for i in range(1)]

You wanted:

blocked_floor1 = [False for i in range(floors) if floors > 0] if floors > 0 else False

Or:

blocked_floor1 = [False for i in range(floors) if floors > 0] if floors > 0 else [False]

The difference being that in the first case, blocked_floor1 will be False, and in the second case it will be [False]. I’d think the first case is preferable, since otherwise you won’t be able to tall if floors was 1 or 0.

However, apart from the syntax error, the whole code seems pointless. In the end, you have a list of floors times False in a list.

So, you might as well:

blocked_floor = [False] * floors if floors > 0 else False  # or, again, [False]

This is probably due to you not providing an example of the problem you’re actually trying to solve though.

Leave a Reply Cancel reply