Reputation: 21
I have a list:
[2, 5, True, 1, 0, 4, False, False, True]
How do I make 1 and 0 show up as 1 and 0 as opposed to True and False? I'm trying to do:
[True if X == True else False for X in list]
Desired result is:
[False, False, True, False, False, False, False, False, True]
Upvotes: 0
Views: 508
Reputation: 2086
This happens because 1 and 0 are "truthy" and "falsey" respectively. You can get around it by using is
which uses the underlying singletons for True and False:
[True if X is True else False for X in list]
Edit: as noted in the comments, it's actually more correct to say that True is "1-like" and False "0-like" in some sense because of the underlying implementation. Less catchy than truthy & falsey though!
Upvotes: 1
Reputation: 11
You need to check the Type of the element by isinstance(X, bool)
So your code will be like this
[True if X == True and isinstance(X, bool) else False for X in list]
Upvotes: 0
Reputation: 350310
You can add a type check:
[isinstance(X, bool) and X for X in list]
NB: the type check should come first, to ensure the expression always evaluates to a boolean.
Upvotes: 1