TrueIntermediate Examples

Boolean literal representing true/1

Truthy values in Python

Understanding all values that evaluate to True.

python
truthy_values = [True, 1, -1, 3.14, "hello", [1], {"a": 1}, {1}, object()]
for val in truthy_values:
    print(f"{str(val):>15} -> bool: {bool(val)}")

Everything that is not falsy is truthy. This includes non-zero numbers, non-empty containers, and all objects.

True in arithmetic

Using True as a number in calculations.

python
print(True + True)
print(True * 10)
print(sum([True, True, False, True]))

# Counting with booleans
words = ["apple", "banana", "avocado", "apricot"]
a_count = sum(w.startswith("a") for w in words)
print(f"Words starting with 'a': {a_count}")
Expected Output
2
10
3
Words starting with 'a': 3

Since bool subclasses int, True acts as 1 in arithmetic. This makes sum() with generator expressions a clean counting idiom.

Want to try these examples interactively?

Open Intermediate Playground