Member-only story
Have you ever wondered why certain expressions evaluate to True
or False
when used as boolean values in your Python programs? This is because of truthy and falsy values in Python. Let's explore what these are and how they work!
Truthy vs. Falsy Values
In Python, every value has either a true or false identity — it’s considered either truthy or falsy. When a value is evaluated as part of a boolean expression, its truthiness or falsiness determines whether the expression evaluates to True
or False
. Here are some common falsy values in Python:
- The integer
0
- An empty string
''
- Empty lists
[]
, tuples()
, sets{}
, dictionaries{}
- None
All other values, including nonzero integers, floating point numbers, strings containing text, and even custom objects, are truthy by default.
Code Examples
Let’s look at some practical examples illustrating truthy and falsy behavior in Python:
bool(42) # True
bool(-3) # True
bool("hello") # True
bool([]) # False
bool({}) # False
bool("") # False
bool(None) # False