Python for Programmers: Truthiness
Welcome to the Truthiness lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
We can call
boolto convert values into booleans. All non-zero numbers (including floats) convert toTrue. Zero numbers like0and0.0convert toFalse. We often say that zero is "falsey" and other numbers are "truthy".>
bool(-3)Result:
True
>
bool(10)Result:
True
>
bool(0)Result:
False
>
bool(0.0)Result:
False
>
bool(0.2)Result:
True
The empty string (
"") is falsey, and all non-empty strings are truthy. Remember, a string that contains spaces is still non-empty!>
bool("")Result:
False
>
bool("Amir")Result:
True
>
bool(" ")Result:
True
Lists are falsey when empty, and truthy when they contain elements. This holds for Python's other collection data types, like tuples and dictionaries.
>
bool(["Amir", "Betty"])Result:
True
>
bool([])Result:
False
Some Python syntax takes a boolean condition, like the
xinif x:orwhile x:. When we use a non-boolean value as the condition, Python automatically converts it into a boolean using the rules that we just saw.>
if -1:condition_passed = Trueelse:condition_passed = Falsecondition_passedResult:
True
>
if []:condition_passed = Trueelse:condition_passed = Falsecondition_passedResult:
False
Every value in Python is either truthy or falsey, with no exceptions. That means that any Python value can technically serve as the condition in an
if.While most real-world
ifs use booleans directly, relying on other values' truthiness is also idiomatic in Python. In particular, we often rely on lists' truthiness to decide whether the list is empty.>
numbers = [2, 3, 6, 8]total = 0while numbers:total += numbers.pop()totalResult:
19
Here's a slight tweak where we explicitly check the list's length, rather than relying on truthiness.
>
numbers = [2, 3, 6, 8]total = 0while len(numbers) > 0:total += numbers.pop()totalResult:
19
We can also rely on the fact that the number 0 is falsey.
>
numbers = [2, 3, 6, 8]total = 0while len(numbers):total += numbers.pop()totalResult:
19
Any of these ways work, but checking length through truthiness (
while numbers:) is most common in Python code. If you're worried that a particular conditional is unclear, it's always fine to do the comparison explicitly, likeif len(numbers) > 0.Although there are many cases to consider, "truthiness" does follow a cohesive rule. Values that represent "nothing" are falsey: zero numbers, empty strings, empty lists, and
Falseitself. Python's null value,None, is also falsey, but we cover it in a different lesson. All other Python values are truthy.