Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Evgeni Tcherkasski
The Python "TypeError: object of type 'bool' has no len()" occurs when we pass
a boolean value (True
or False
) to the len()
function. To solve the error,
make sure you aren't evaluating an expression in the call to the len()
function.
Here is an example of how the error occurs.
my_bool = True # ⛔️ TypeError: object of type 'bool' has no len() print(len(my_bool))
We passed a boolean (True
or False
) to the len()
function which caused the
error.
Make sure you aren't evaluating an expression in the call to the len()
function.
my_bool = True # ⛔️ TypeError: object of type 'bool' has no len() if len('hi' == 'hi'): print('success')
The expression 'hi' == 'hi'
evaluates to True
, so we end up passing a
boolean to the len
function.
Instead, you can call the len()
function which each value.
my_bool = True if len('hi') == len('hi'): # 👇️ this runs print('success')
The len() function returns the length (the number of items) of an object.
my_list = ['apple', 'banana', 'kiwi'] result = len(my_list) print(result) # 👉️ 3
Notice that the len()
function cannot be called with a boolean.
If you didn't expect the variable to store a boolean value, you have to correct the assignment.
If you aren't sure what type a variable stores, use the built-in type()
class.
my_bool = False print(type(my_bool)) # 👉️ <class 'bool'> print(isinstance(my_bool, bool)) # 👉️ True
The type class returns the type of an object.
The isinstance
function returns True
if the passed in object is an instance or a subclass of
the passed in class.
When we pass an object to the len() function, the object's __len__() method is called.
You can use the dir()
function to print an object's attributes and look for
the __len__
attribute.
my_bool = True print(dir(my_bool))
Or you can check using a try/except
statement.
my_bool = True try: print(my_bool.__len__) except AttributeError: # 👇️ this runs print('object has no attribute __len__')
We try to access the object's __len__
attribute in the try
block and if an
AttributeError
is raised, we know the object doesn't have a __len__
attribute and cannot be passed to the len()
function.