There are 2 built-in Boolean objects in Python-
- True
- False
If we convert any other data type to Boolean, it will be either True or False.
Create Boolean
We can use the “bool” function to create a boolean. If no param is provided then it returns false-
big_box_bool = bool()
print(big_box_bool)
print(type(big_box_bool))
second_bool = bool(True)
print(second_bool)
third_bool = bool(False)
print(third_bool)
fourth_bool = bool(100)
print(fourth_bool)
PythonOutput:
False
<class 'bool'>
True
False
True
PlaintextOr we can just assign a Boolean value – True or False, to a variable.
big_box_bool = True
print(big_box_bool)
second_bool = False
print(second_bool)
PythonOutput:
True
False
PlaintextBoolean Reassignment Internals
Let’s create some boolean variables and check their internal ID.
first_bool = True
print("first_bool: ", id(first_bool))
second_bool = False
print("second_bool: ", id(second_bool))
third_bool = True
print("third_bool: ", id(third_bool))
fourth_bool = False
print("fourth_bool: ", id(fourth_bool))
fifth_bool = True
print("fifth_bool: ", id(fifth_bool))
PythonOutput:
All the True values have same ID and all the false values have the same ID. Because all True variables refer to the same object in memory and same for the False variables.
first_bool: 140727304839568
second_bool: 140727304839600
third_bool: 140727304839568
fourth_bool: 140727304839600
fifth_bool: 140727304839568
PlaintextHere is how it looks in memory-
Now let’s see what happens when we change the value of a boolean variable-
import ctypes
big_box_bool = True
first_id = id(big_box_bool)
print("Initial id: ", first_id)
big_box_bool = False
print("ID after change: ", id(big_box_bool))
obj = ctypes.cast(first_id, ctypes.py_object)
print("Old boolean object: ", obj)
PythonOutput:
When reassigned, the variable will point to a new object in memory. And the previous boolean object remains the same in memory.
Initial id: 140727304839568
ID after change: 140727304839600
Old boolean object: py_object(True)
PlaintextHere is how the reassignment operation looks in memory-