Python for Programmers: Booleans as Integers
Welcome to the Booleans as Integers lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Internally, Python represents booleans as integers.
Trueis represented by1, andFalseby0. Callinginton a boolean converts it to the corresponding integer.>
[int(True), int(False)]Result:
[1, 0]
>
True + True + FalseResult:
2
Sometimes you'll see this used (some would say abused) in real-world code. For example, we might have a list of dictionaries, and want to count how many dictionaries are not empty.
Remember, an empty dictionary is falsey. Converting it into an
boolgives usFalse, and converting thatboolinto anintgives us0.>
a_dict = {}bool(a_dict)Result:
False
>
a_dict = {}int(bool(a_dict))Result:
0
>
a_dict = {"foo": "bar"}int(bool(a_dict))Result:
1
Knowing this, we can check each dictionary in an
ifstatement. If it's empty, it'll be false!>
users = [{"name": "Amir"},{"name": "Betty"},{},]- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
user_count = 0for user in users:if user:user_count += 1user_countResult:
2
Or we can use the "booleans as integers" trick.
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
sum([bool(user) for user in users])Result:
2
Let's review what happened there:
bool(user)returnedFalsefor empty user dictionaries andTruefor non-empty dictionaries.- We called
sum, which ultimately added the values together with+. SinceTrueis1andFalseis0, callingsumon a list of booleans counts the number ofTrues.
The second version of our code is certainly shorter than the loop-based version! But optimizing for the fewest lines of code is rarely a good idea. In this case, there's a less-clever solution that's only slightly longer.
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
len([user for user in users if user])Result:
2
Different programmers will have different opinions about the
if userin that comprehension. Some think that it's a fine way to check for an empty dictionary. Others prefer a more explicit "is this dictionary empty?" check. The latter group might write this code instead:- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
len([user for user in users if len(user) > 0])Result:
2
All of the comprehension-based solutions here are shorter than our first version with the
forloop. Of these four solutions, we'd recommend one of the last two. We want our code to be terse, but we also want it to be clear. The last two solutions both strike a good balance.