Home > Back-end >  Why is this if/else list comprehension not working?
Why is this if/else list comprehension not working?

Time:09-03

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:

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

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

CodePudding user response:

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']
  • Related