4

In Python, variables have truthy values based on their content. For example:

>>> def a(x):
...     if x:
...         print (True)
... 
>>> a('')
>>> a(0)
>>> a('a')
True
>>> 
>>> a([])
>>> a([1])
True
>>> a([None])
True
>>> a([0])
True

I also know I can print the truthy value of a comparison without the if operator at all:

>>> print (1==1)
True
>>> print (1<5)
True
>>> print (5<1)
False

But how can I print the True / False value of a variable? Currently, I'm doing this:

print (not not a)

but that looks a little inelegant. Is there a preferred way?

Tim
  • 2,141
  • 1
  • 20
  • 30
  • `bool` is the way to go, but I like the `not not` hack :) – Craig Burgler Sep 20 '16 at 22:38
  • 1
    @CraigBurgler -- the `not not` hack is used a lot in Javascript... `!!whatever` is a pretty standard idiom for "give me the 'boolean-ness' of whatever". I've never seen it in Python though :-) – mgilson Sep 20 '16 at 22:40
  • there is also `True if a else False` ... but use bool :) – wim Sep 20 '16 at 22:43
  • @mgilson: It could be marginally useful in cases where you want to microoptimize the global lookup and function call, since [`not not x` is a bit faster than `bool(x)`](http://ideone.com/CFYruw), but I've never actually seen it in practice. Cases where that kind of microoptimization would matter are pretty rare. – user2357112 supports Monica Sep 20 '16 at 22:52

1 Answers1

5

Use the builtin bool type.

print(bool(a))

Some examples from the REPL:

>>> print(bool(''))
False
>>> print(bool('a'))
True
>>> print(bool([]))
False
mgilson
  • 264,617
  • 51
  • 541
  • 636
  • 1
    Nice. Is there a name for this inherent truthyness to variables - so I could more easily search next time? – Tim Sep 20 '16 at 22:37
  • @Tim -- Hmmm ... No "names" are really coming to mind. In this case, I might have asked Google how to construct a boolean from an instance of something. – mgilson Sep 20 '16 at 22:40
  • I wondered that too. If you ever find it, please rename ["boolness"](http://stackoverflow.com/questions/8205558/defining-boolness-of-a-class-in-python) question .. – wim Sep 20 '16 at 22:45
  • 1
    @Tim The name may be `truth value` as per the first section of the `Built-in Types` doc: https://docs.python.org/3.4/library/stdtypes.html – Craig Burgler Sep 20 '16 at 22:53
  • @CraigBurgler In that case, http://stackoverflow.com/questions/18491777 is Related but not a duplicate - as it is not asking about printing it. Leaving it here for the sidebar. – Tim Sep 20 '16 at 22:55
  • Always important to note: `bool([False])==True` – kylieCatt Sep 20 '16 at 22:58
  • @IanAuld Yes, it's a non-empty list. Just as `bool([0])` and `bool(['']` are `True`. – Tim Sep 20 '16 at 22:59