Determining Truthiness of Non-Boolean Types
In this lesson, you will learn how Python treats non-Boolean data—like numbers, strings, and lists—as either True or False when they appear in logical conditions.
The Concept of Implicit Truthiness
In Python, you don’t always need a comparison operator (like == or >) to check if a value exists. Python has a built-in rule: most things are considered True, but "empty" or "zero" things are considered False. This allows you to write cleaner, more readable code.
What is "False"?
Python considers the following values to be falsy (they evaluate to False in a condition):
- Zero values:
0,0.0 - Empty sequences or collections:
""(empty string),[](empty list) - Special constants:
None,False
Everything else, such as a string with text, a list with items, or a non-zero number, is considered truthy.
Putting it into Practice
You can use this behavior directly inside an if statement to check if a variable has content. For example, instead of checking if a list is empty by measuring its length, you can simply evaluate the list itself:
user_input = ""
items = ["apple", "banana"]
# Check if the string is NOT empty
if user_input:
print("User entered something!")
else:
print("The input is empty.")
# Check if the list has items
if items:
print(f"You have {len(items)} items in your list.")
In the example above, if user_input: fails because an empty string is falsy. Meanwhile, if items: succeeds because the list contains data, making it truthy. This is a common, idiomatic way to write Python code because it keeps your logic concise without needing to explicitly compare values against "" or 0.
Key Takeaway: In Python, empty collections, zero values, and empty strings are treated as False, while all other objects are treated as True.