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

Why is this if/else list comprehension not working?

i have list with booleans (True, False), strings (‘TRUE’, ‘FALSE) and also ‘VOID’

x = [True, False, True, 'TRUE', 'FALSE', 'VOID']

i wish to change everything to a bool value aside from ‘Void’. I am trying to use the following list comprehension but it breaks on the ‘else’ part no matter what:

c = [bool(z) for z in x if z is True or z is False or z == 'TRUE' or z == 'FALSE' else z for z in x]

there are many similar posts eg if/else in a list comprehension which gives the generalisation:

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

[f(x) if condition else g(x) for x in sequence]

but its clear that it does not work here. Any one know why?

>Solution :

Following the generalization you wrote in the question, your list comprehension should be:

c = [bool(z) if z is True or z is False or z == 'TRUE' or z == 'FALSE' else z for z in x]

with output

[True, False, True, True, True, 'VOID']
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