0

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]
user38283
  • 21
  • 2
  • 2
    What's wrong with `[x is True for x in lst]` ? – jpp Oct 13 '20 at 10:24
  • Related (or a duplicate...): https://stackoverflow.com/questions/2764017/is-false-0-and-true-1-an-implementation-detail-or-is-it-guaranteed-by-the – Tomerikoo Oct 13 '20 at 10:33

3 Answers3

1

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!

PirateNinjas
  • 1,908
  • 1
  • 16
  • 21
  • 4
    Actually, it's not because of truthiness. E.g. `[] == True` is false. This is because `bool` is a subclass of `int` with exactly two integers: 1, and 0, i.e. True and False – juanpa.arrivillaga Oct 13 '20 at 10:19
  • Good answer. Thanks. Answered based on format given as opposed to being too creative. – user38283 Oct 13 '20 at 10:33
  • @user38283 Out of all the answers, you picked the one that matches your beginner style of code, no criticism implied here. However with getting a little more creative, you get answers that don't perform a whole bunch of unnecessary checks. – solid.py Oct 13 '20 at 10:43
  • The answer fit my problem. I could very well have another situation where I don't want a resulting vector of only True False (maybe True and other items), so other answers wouldn't apply. The answer allows me to customize it for my purpose. – user38283 Oct 13 '20 at 10:48
1

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
0

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]