What are the true and false criteria for a python object?
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.
source to share