Why is it that in Python integers and floats are, without being evaluated in a boolean context, equivalent to True? Other data types have to be evaluated via an operator or bool().
4 Answers
That's not True:
>>> print("True" if 1 else "False")
True
>>> print("True" if 0 else "False")
False
>>> print("True" if 0.0 else "False")
False
>>> print("True" if 123.456 else "False")
True
>>> print("True" if "hello" else "False")
True
>>> print("True" if "" else "False")
False
>>> print("True" if [1,2,3] else "False")
True
>>> print("True" if [] else "False")
False
>>> print("True" if [[]] else "False")
True
Only non-zero numbers (or non-empty sequences/container types) evaluate to True.
2 Comments
Basic
I think you mean non-zero numbers.
Sukrit Kalra
Adding on your answer.
string can be checked through a similar way. So, it's not only integers and floats.Here is a use case -
>>> bool(2)
True
>>> bool(-3.1)
True
>>> bool(0)
False
>>> bool(0.0)
False
>>> bool(None)
False
>>> bool('')
False
>>> bool('0')
True
>>> bool('False')
True
>>> bool([])
False
>>> bool([0])
True
In Python, these are False -
- The Boolean value
Falseitself - Any numerical value equal to 0 (0, 0.0 but not 2 or -3.1)
- The special value
None - Any empty sequence or collection, including the empty string(
'', but not'0'or'hi'or'False') and the empty list ([], but not[1,2, 3]or[0])
Rest would evaluate to True. Read more.
Comments
From Python Documentation 5.1:
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
- None
- False
- zero of any numeric type, for example,
0,0L,0.0,0j. - any empty sequence, for example,
'',(),[]. - any empty mapping, for example,
{}. - instances of user-defined classes, if the class defines a
__nonzero__()or__len__()method, when that method returns the integer zero or bool value False.
Why? Because it's handy when iterating through objects, cycling through loops, checking if a value is empty, etc. Overall, it adds some options to how you write code.
0and0.0don't evaluate toTrue