TypeError: object of type 'float' has no len() in Python


Borislav Hadzhiev

Last updated: Apr 20, 2022


Check out my new book

TypeError: object of type 'float' has no len() in Python #

The Python "TypeError: object of type 'float' has no len()" occurs when we pass a float to the len() function. To solve the error, figure out where the variable got assigned a float and correct the assignment or convert the float to a string.

typeerror object of type float has no len

Here is an example of how the error occurs.

my_float = 3.14 # ⛔️ TypeError: object of type 'float' has no len() print(len(my_float))

We passed a floating-point number to the len() function which caused the error.

If you need to get the length of a float, convert it to a string first.

my_float = 3.14 print(len(str(my_float))) # 👉️ 4

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
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

Notice that the len() function cannot be called with a floating-point number.

If you didn't expect the variable to store a float, you have to correct the assignment.

If you are trying to iterate a specific number of times, use the range() class.

my_float = 3.14 for n in range(int(my_float)): print(n) result = list(range(int(my_float))) # 👇️ [0, 1, 2] print(result)

The range class is commonly used for looping a specific number of times in for loops and takes the following parameters:

startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

Note that 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_float = 3.14 print(dir(my_float))

Or you can check using a try/except statement.

my_float = 3.14 try: print(my_float.__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.

If you aren't sure what type a variable stores, use the built-in type() class.

my_float = 3.14 print(type(my_float)) # 👉️ <class 'float'> print(isinstance(my_float, float)) # 👉️ 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.