What are the true and false criteria for a python object?
I've seen the following cases:
>>> def func(a):
... if a:
... print("True")
...
>>> a = [1, 2, 3]
>>> func(a)
True
>>> a == True
False
Why does this difference arise?
All 1 objects in Python have a truth value :
Any object can be tested for true, for use in a state
if
orwhile
or as an operand for the logical operations below. The following values ββare considered false:
None
False
- zero any numeric type, for example
0
,0.0
,0j
.- Any empty sequence, for example
''
,()
,[]
.any empty display eg
{}
.instances of custom classes, if the class defines a method,
__bool__()
or__len__()
when that method returns an integer 0 or a bool valueFalse
.All other values ββare considered true, so objects of many types are always true.
1 ... unless they have a method __bool__()
that throws an exception, or returns a value other than True
or False
. The first is unusual, but sometimes reasonable behavior (for example, see user2357112's comment below); the latter is not.
When entered, if a:
it is equivalent if bool(a):
. Thus, this does not mean that a is True
, only the presentation a
as a boolean value True
.
Generally speaking, bool
is a subclass int
where True == 1
and False == 0
.