Python: Boolean [Data Type]

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)
Python

Output:

False
<class 'bool'>
True
False
True
Plaintext

Or 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)
Python

Output:

True
False
Plaintext

Boolean 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))
Python

Output:

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
Plaintext

Here is how it looks in memory-

Python Boolean Internal ID
Python Boolean Internal ID

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)
Python

Output:

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)
Plaintext

Here is how the reassignment operation looks in memory-

Python Boolean Reassignment
Python Boolean Reassignment

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.