Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List comprehension in Python : if else not working

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading