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 (
False) to the
len() function. To solve the error,
make sure you aren't evaluating an expression in the call to the
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 (
False) to the
len() function which caused the
Make sure you aren't evaluating an expression in the call to the
my_bool = True # ⛔️ TypeError: object of type 'bool' has no len() if len('hi' == 'hi'): print('success')
'hi' == 'hi' evaluates to
True, so we end up passing a
boolean to the
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
my_bool = False print(type(my_bool)) # 👉️ <class 'bool'> print(isinstance(my_bool, bool)) # 👉️ True
The type class returns the type of an object.
True if the passed in object is an instance or a subclass of
the passed in class.
You can use the
dir() function to print an object's attributes and look for
my_bool = True print(dir(my_bool))
Or you can check using a
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
attribute and cannot be passed to the