liveBook · Manning

Truthiness

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A truthy value is a Python value that evaluates to true in a Boolean context.

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

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines falsey and truthy values, demonstrates operand-returning operators, and stops short of custom truth-value behavior.
Examples
Demonstrates regex match groups, consonant filtering, car selection, numeric ranges, and Tic-Tac-Toe argument validation.
What you can do after
Apply truthiness via logical operators, comprehensions, filter(), any(), and all() to write concise selection and validation code.
How it connects
Connects truthiness with Boolean contexts, logical operators, list comprehensions, filter(), any(), and all().

Also explained in

Compare how 6 books explain truthiness →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.