Truthiness lets Python evaluate values in Boolean contexts, so conditions are not limited to True and False. Non-empty strings, nonzero numbers, and non-empty collections are truthy; '', 0, 0.0, [], and {} are falsey. section 14.5
Use truthiness when selecting values or filtering data:
- The or operator returns the first truthy operand, while and returns a truthy or falsey operand rather than necessarily returning a Boolean. section 14.1.4 section 21.2.1
- List-comprehension guards and filter() retain only elements whose tests return truthy values. section 14.3.1
- any() succeeds when at least one item is truthy; all() succeeds only when every item is truthy. section 21.2.1
Choosing a fallback
A regular-expression match group can be absent, so use an empty string as its fallback: p1 = match.group(1) or ''. With a match, the group is returned; otherwise, '' supplies the falsey alternative. section 14.1.4
>>> True or False #1
True
>>> False or True #2
True
>>> 1 or 0 #3
1
>>> 0 or 1 #4
1
>>> 0.0 or 1.0 #5
1.0
>>> '0' or '' #6
'0'
>>> 0 or False #7
False
>>> [] or ['foo'] #8
['foo']
>>> {} or dict(foo=1) #9
{'foo': 1}
Compare or with Boolean values, numbers, strings, lists, and dictionaries to see which operand is returned. section 14.1.4





