The Hidden Integer Nature of Python Booleans
Take a look at the above python code. What will be the output of this code?
If you got it right clap for yourself. If not, still do it because you are going to learn something interesting today.
If you think integers are the only valid indexes for a list, then you are absolutely correct. But this will not throw an error because Python allows booleans to behave like indexes.
Why does Python allow booleans as indexes if indexing expects integers?
What is Truthiness?
First learn about Booleans and their truthiness.
Python internally evaluates every objects or expressions as True or False. There is a limited set of values that are considered as False in Python. Empty collections, zero-like values and None are considered False.
bool(None) # False
bool(0) # False
bool(0.0) # False
bool(0j) # False
bool([]) #Empty List, False
bool(tuple()) # Empty Tuple, False
bool({}) # Empty Dict, False
bool(set()) # Empty Set, False
bool('') # Empty String, False
a = range(0) # Empty range, False
print(bool(a))
print(bool()) # Empty bool function, FalseOther than these values, everything in Python are evaluated as True. Even built-in function objects and classes and user defined classes and objects are True. (Although user defined classes and objects can be changed to False using bool dunder method)
However, booleans themselves have a deeper internal behaviour.
Key Concept
Boolean types are subclass of int datatype. They are considered as special numeric datatype.
print(isinstance(True, int)) # True
print(True == 1) # True
print(False == 0) # TrueThis allows them to behave like integers in arithmetic operations and indexing.
print(True + True) # 2
print(False + 5) # 5Explanation of the Code
True behaves numerically as 1 and False as 0.
That’s why
lst = ['hello', 'world']
print(lst[True] == lst[1]) # TrueSince True behaves numerically as 1, both expressions access the same element.
Get S Chand’s stories in your inbox
Join Medium for free to get updates from this writer.
But that does not mean, True and False are numeric datatype or plain integers, they are still bool type.
print(type(True)) # <class 'bool'>Some more Examples
Example 1:
lst = [1,2,3,4,5]
print(lst[True + True + True]) # 4Example 2:
messages = ['Access denied', 'Access granted']
is_admin = True
print(messages[is_admin]) #Acces grantedExample 3:
canMail = True
canCall = True
canMessage = True
canMeet = False
canPost = False
waysToContact = [canMail, canCall, canMessage, canMeet, canPost]
print(f'Number of ways to contact: {sum(waysToContact)}')
# Number of ways to contact: 3Caveat: There is a Catch
Although using booleans directly in indexing looks interesting but it can reduce readability so writing detailed code is better and easy to understand.
lst = ['First', 'Second']
condition = True
print(lst[condition])
print(lst[1 if condition else 0])


