How to Resolve Python Error "TypeError: object of type 'int'/'float'/'bool' has no len()"
The TypeError: object of type 'X' has no len()
(where X
is commonly int
, float
, or bool
) is a fundamental Python error indicating that you tried to use the built-in len()
function on a data type that doesn't have a defined length. The len()
function is designed to work with sequences (like strings, lists, tuples) and collections (like dictionaries, sets) that have a countable number of items.
This guide explains why numbers and booleans don't have a length and provides solutions for common scenarios where this error occurs.
Understanding the Error: What len()
Measures
The built-in len()
function in Python is used to determine the "length" of an object, which generally means the number of items it contains. It works by internally calling the object's special __len__()
method.
len()
is defined for:
- Sequences: Strings (number of characters), lists (number of elements), tuples (number of elements), range objects (number of integers they produce), bytes (number of bytes).
- Collections: Dictionaries (number of key-value pairs), sets (number of unique elements).
Crucially, fundamental data types like integers (int
), floating-point numbers (float
), and booleans (bool
) do not have an intrinsic concept of "length" in this way. They represent single values, not collections of items. Therefore, they do not implement the __len__()
method, and passing them to len()
results in the TypeError
.
Cause 1: Passing Numeric Types (int
, float
) to len()
Directly passing an integer or float to len()
causes the error.
Error Scenario
count = 150
price = 99.95
try:
# ⛔️ TypeError: object of type 'int' has no len()
length_of_count = len(count)
print(length_of_count)
except TypeError as e:
print(f"Integer Error: {e}")
try:
# ⛔️ TypeError: object of type 'float' has no len()
length_of_price = len(price)
print(length_of_price)
except TypeError as e:
print(f"Float Error: {e}")
Solution: Find Length of String Representation (len(str(number))
)
If your goal is to find the number of digits (including the decimal point and sign for floats) in the number's textual representation, first convert the number to a string using str()
, then find the length of that string.
count = 12345
price = -199.99
# ✅ Convert int to string, then get length
count_str_len = len(str(count))
print(f"Number of digits in {count}: {count_str_len}") # Output: 5
# ✅ Convert float to string, then get length
price_str_len = len(str(price))
print(f"Length of string representation of {price}: {price_str_len}") # Output: 7 ('-', '1', '9', '9', '.', '9', '9')
# If excluding the decimal point for floats:
if isinstance(price, float) and '.' in str(price):
price_digits_len = len(str(price)) - str(price).count('.') # Count and subtract decimal points
print(f"Approx digit count for {price}: {price_digits_len}") # Output: 6
Output:
Number of digits in 12345: 5
Length of string representation of -199.99: 7
Approx digit count for -199.99: 6
Alternative: Use range()
for Iteration Count
If you were trying to use len(my_number)
to control a for
loop, you likely intended to use the range()
function instead. range(n)
creates an iterable sequence from 0 up to (but not including) n
.
# Incorrect intent: Trying to loop 'count' times using len()
count = 5
# for i in len(count): # Raises TypeError
# ✅ Correct: Use range() to loop 'count' times
print(f"Looping {count} times:")
for i in range(count):
print(f" Iteration {i}")
# Output: Iteration 0, 1, 2, 3, 4
Output:
Looping 5 times:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Cause 2: Passing Booleans (bool
) to len()
Booleans (True
, False
) also lack a defined length.
Error Scenario
is_enabled = True
try:
# ⛔️ TypeError: object of type 'bool' has no len()
length_of_bool = len(is_enabled)
print(length_of_bool)
except TypeError as e:
print(e)
Output:
object of type 'bool' has no len()
Common Mistake: Calling len()
on a Comparison Result
A frequent source of this error is accidentally applying len()
to the result of a comparison (which is always True
or False
), instead of applying len()
to the operands before the comparison.
string1 = "hello"
string2 = "world"
try:
# Incorrect: len() applied to the result of the comparison (False)
# ⛔️ TypeError: object of type 'bool' has no len()
if len(string1 == string2):
print("Comparison result has length?") # This code is logically flawed
except TypeError as e:
print(f"Error comparing lengths incorrectly: {e}")
# ✅ Correct: Apply len() to each string, then compare the lengths
if len(string1) == len(string2):
print("Strings have the same length.")
else:
print("Strings have different lengths.") # This is executed
Output:
Error comparing lengths incorrectly: object of type 'bool' has no len()
Strings have the same length.
Solution: Apply len()
Before Comparison
Ensure you call len()
on the sequence/collection objects first, and then compare the resulting integer lengths if needed.
Cause 3: Accidental Variable Reassignment
A variable that initially held a sequence (like a list or string) might have been unintentionally reassigned to an integer, float, or boolean value later in the code.
Error Scenario
data = ["item1", "item2"] # Initially a list
print(f"Initial type: {type(data)}") # <class 'list'>
# ... some logic ...
data_is_valid = True # Some check result
data = data_is_valid # ⚠️ Accidental reassignment overwrites the list!
print(f"Type after reassignment: {type(data)}") # <class 'bool'>
# ... later ...
try:
# ⛔️ TypeError: object of type 'bool' has no len()
# Trying to get length of the variable 'data', which now holds True
num_items = len(data)
print(f"Number of items: {num_items}")
except TypeError as e:
print(e)
Output:
Initial type: <class 'list'>
Type after reassignment: <class 'bool'>
object of type 'bool' has no len()
Solution: Trace and Correct Assignment
Find where the variable was incorrectly reassigned and fix the logic. Use different variable names if necessary to store intermediate boolean flags or numeric results without overwriting variables holding sequences or collections.
Debugging the Error (type()
, hasattr()
)
- Check Type: When
len()
raises thisTypeError
, immediately check the type of the object you passed to it:This will confirm it'sprint(f"DEBUG: Type of variable passed to len() is {type(variable_name)}")
<class 'int'>
,<class 'float'>
, or<class 'bool'>
. - Check for
__len__
: Objects compatible withlen()
have a__len__()
method. You can check for its presence (though checking the type is usually more direct).value = 100
if hasattr(value, '__len__'):
print("Object has __len__, should work with len()")
else:
# This runs for int, float, bool
print("Object does not have __len__, will cause TypeError with len()") - Trace Assignment: If the type is unexpected, trace the variable back through your code to find where it acquired the problematic numeric or boolean value.
Conclusion
The TypeError: object of type 'int'/'float'/'bool' has no len()
occurs because the len()
function requires an argument that represents a sequence or collection with a defined number of items. Numbers and booleans are single values and do not have this property.
To fix this error:
- Do not pass
int
,float
, orbool
values directly tolen()
. - If you need the number of digits in a number's representation, convert it to a string first using
str()
, then get the length:len(str(number))
. - If you intended to use
len()
as part of a comparison, ensure you applylen()
to the sequences/collections before comparing the resulting lengths. - If the variable was not supposed to hold a number or boolean, find and fix the incorrect assignment in your code.
- If trying to loop a specific number of times, use
range(number)
instead oflen(number)
.
By understanding what len()
expects and ensuring you provide a compatible type (string, list, tuple, dict, set, etc.), you can avoid this common TypeError
.