bool([]) will output False. This behavior is a core concept in Python known as "truthiness," where various values are implicitly interpreted as either True or False in a boolean context.
Python's truth value testing
In Python, the built-in bool() function returns True for "truthy" values and False for "falsy" values. An empty list ([]) is considered a "falsy" value, along with other empty collections and zero-like values.
The conversion from a list to a boolean happens implicitly in several situations, most notably in if and while statements.
Example:
# An empty list is falsy
my_list = []
if my_list:
print("This list is not empty.")
else:
print("This list is empty.")
# Output:
# This list is empty.
# A non-empty list is truthy
my_list = [1, 2, 3]
if my_list:
print("This list is not empty.")
else:
print("This list is empty.")
# Output:
# This list is not empty.
Use code with caution.
The role of __len__
For objects that have a length, such as lists, tuples, and strings, Python's truth testing procedure relies on the object's __len__() method.
- If an object's
__len__()method returns0, the object is considered "falsy." - If
__len__()returns any non-zero value, the object is "truthy".
Since an empty list [] has a length of 0, bool([]) returns False.
# The length of an empty list is 0
my_list = []
print(len(my_list))
# Output: 0
# Which evaluates to False
print(bool(len(my_list)))
# Output: False
Use code with caution.
Other falsy values in Python
Besides the empty list, other common falsy values in Python include:
NoneFalse(of course)- The integer
0, floating-point0.0, and complex number0j - Empty sequences like
''(empty string) and()(empty tuple) - Empty collections like
{}(empty dictionary) andset()(empty set)
Importance of understanding truthiness
Understanding Python's truthiness rules is crucial for writing concise and readable code. The "Pythonic" way to check if a list is empty is to use its intrinsic boolean value, as if my_list: is more efficient and elegant than if len(my_list) > 0:.
Correct and Pythonic:
if not my_list:
print("The list is empty.")
Use code with caution.
Alternative (less Pythonic):
if len(my_list) == 0:
print("The list is empty.")
Use code with caution.
A special case: Nested empty lists
It is important to remember that the truthiness of an object is based on its own emptiness, not the emptiness of its contents. For example, a list containing only empty lists is still considered "truthy" because the outer list itself is not empty.
nested_list = [[], [], []]
# The list itself is not empty, so its boolean value is True
print(bool(nested_list))
# Output: True
if nested_list:
print("The nested list is not empty.")
# Output: The nested list is not empty.
Use code with caution.