Python's `truthy` and `falsy`
This article explains Python's truthy and falsy.
YouTube Video
Python's truthy and falsy
Definition of truthy and falsy
In Python, objects evaluated in conditional expressions are deemed either 'True' or 'False'. Truthy refers to objects evaluated as 'True', and falsy refers to those evaluated as 'False'. These evaluations are often used in conditional branches such as if statements or while loops. Also, the bool() function takes any object and returns its Boolean value.
Falsy (Objects evaluated as False)
In Python, the following objects are considered falsy:.
-
False -
None -
Numeric zero values
- Example:
0,0.0
- Example:
-
Empty sequence types (such as empty lists, tuples, or strings)
- Example:
[],(),""
- Example:
-
Empty dictionary
- Example:
{}
- Example:
-
Empty set
- Example:
set()
- Example:
These objects are evaluated as 'falsy' when used in the condition of an if statement. For example, you can write code like this.
1if not []:
2 print("The list is falsy.")- In this code, the list
[]is empty, so it is evaluated asfalsy, and theprintstatement is executed.
Truthy (Objects evaluated as True)
Objects that are not considered falsy are regarded as truthy.
-
Non-zero numbers (integers, floating-point numbers)
- Examples:
1,3.14,-100
- Examples:
-
Non-empty sequence types (lists, tuples, strings, etc.)
- Examples:
[1, 2, 3],(1, 2),"Hello"
- Examples:
-
Non-empty dictionaries
- Example:
{"key": "value"}
- Example:
-
Non-empty sets
- Example:
{1, 2, 3}
- Example:
Objects considered truthy will evaluate as 'True' when used in the condition of an if statement. For example, you can write code like this.
1if [1, 2, 3]:
2 print("The list is truthy.")- In the code above, since the list
[1, 2, 3]is not empty, it is evaluated astruthyand theprintstatement is executed.
Evaluating Boolean value with the bool() function
You can evaluate the Boolean value of objects by using the bool() function.
1# Examples of falsy values
2print("False is", "truthy" if bool(False) else "falsy")
3print("0 is", "truthy" if bool(0) else "falsy")
4print('"" is', "truthy" if bool("") else "falsy")
5print("None is", "truthy" if bool(None) else "falsy")
6print("[] is", "truthy" if bool([]) else "falsy")
7
8# Examples of truthy values
9print("1 is", "truthy" if bool(1) else "falsy")
10print('"hello" is', "truthy" if bool("hello") else "falsy")
11print('" " (space) is', "truthy" if bool(" ") else "falsy")
12print('"0" is', "truthy" if bool("0") else "falsy")- This code demonstrates how the truth value of various values is evaluated. For example, the numeric value
0and an empty string are consideredFalse, while a space or the string"0"are consideredTrue.
Utilizing truthy and falsy
By utilizing truthy and falsy, code can be written more concisely and intuitively. In particular, if statements can often be evaluated without explicit comparisons to make them shorter. For example, the following two pieces of code behave similarly, but the first one is more concise.
1my_list = [1]
2
3# Explicit comparison
4if my_list != []:
5 print("The list is not empty.")
6
7# Using truthy/falsy
8if my_list:
9 print("The list is not empty.")In the example above, you can see that my_list is evaluated as truthy as long as it is not an empty list, which eliminates the need for explicit comparison.
Designing with truthy and falsy
By effectively utilizing the concepts of truthy and falsy, you can enhance code readability and efficiency. They are particularly useful for setting default values, checking variable validity, and input validation. For example, if you expect None or an empty list to be passed as arguments, you can write code like this.
1def process_data(data=None):
2 data = data or []
3 print(data)
4
5process_data() # An empty list is used by default.- In this code, if
dataisNone, an empty list[]is set as the default value. In this way, usingtruthyandfalsyallows you to set default values concisely.
Points to note to avoid unintended behavior
However, while code that uses truthy and falsy values can be concise and convenient, be aware that it may cause unintended behavior. For example, in this code, not only when data is None, but also when it is any value evaluated as False, such as an empty string or 0, it will be replaced with the default empty list []. For this reason, when a stricter condition is required, such as initializing only when the value is None, it is recommended to use an explicit condition like value is None:. Depending on the situation, it is important to design with a balance between conciseness and rigor in mind.
1def process_data(data=None):
2 if data is None:
3 data = []
4 print(data)
5
6process_data() # An empty list is used by default.
7process_data(0) # 0 is printed because it's not None.- In this code,
datais initialized to an empty list only if it isNone, while other falsy values like0are left as-is.
Controlling Boolean value in custom objects
Even in your own classes, you can control the Boolean value of an instance by defining __bool__() or __len__().
1class MyContainer:
2 def __init__(self, items):
3 self.items = items
4
5 def __len__(self):
6 return len(self.items)
7
8box = MyContainer([])
9print(bool(box)) # False
10
11box.items.append("item")
12print(bool(box)) # True- In this code, the
__len__()method causes the container to be evaluated asFalsewhen it is empty, andTruewhen it has elements.
Conclusion
The concepts of truthy and falsy in Python are very important for writing concise conditional expressions and making the code more intuitive. Understanding and properly using these can greatly enhance code readability and efficiency.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.