askvity

Is True 1 in Python?

Published in Python Booleans 2 mins read

Yes, True is equivalent to 1 in Python.

Understanding Boolean Values in Python

In Python, boolean values represent truth or falsehood. Python has two built-in boolean constants: True and False. These constants are subclasses of integers, and they behave numerically as 1 and 0, respectively. This means you can use True and False in arithmetic operations, and Python will treat them as their integer equivalents.

Demonstration

Here's a simple demonstration:

print(True == 1)
print(False == 0)
print(True + 1)
print(False + 5)

Output:

True
True
2
5

As demonstrated, True is indeed equal to 1, and False is equal to 0. Adding boolean values to integers works as expected, with True contributing 1 and False contributing 0 to the result.

Practical Implications

This behavior can be useful in certain situations. For example, you can count the number of True values in a list of boolean values by summing the list.

bool_list = [True, False, True, True, False]
count_true = sum(bool_list)
print(count_true)

Output:

3

Here, summing the bool_list provides an efficient way to determine the number of True values, as each True contributes 1 to the sum.

Important Note

While True and 1 are equivalent, it is generally considered good practice to use True and False for boolean logic and 1 and 0 for numerical calculations to maintain code clarity and readability.

Related Articles