How to Solve Python TypeError: object of type ‘float’ has no len()

by | Programming, Python, Tips

This error occurs when you pass a float to a len() function call. Floats are real numbers written with a decimal point dividing the integer and fractional parts. In Python, numerical values do not have a length.

You can solve the error by only passing iterable objects to the len() function. For example, you can convert a float to an int using int() and then pass the value to a range() function call to get a range object, which is iterable and has a length. For example,

my_float = 5.3

my_int = int(round(my_float,0))

rng = range(my_int)

print(len(rng))

You can check what the type of an object is before calling len() using the type() function.

This tutorial will go through the error and how to solve it with code examples.


TypeError: object of type ‘float’ has no len()

We raise a Python TypeError when attempting to perform an illegal operation for a specific type. In this case, the type is int.

The part ‘has no len()‘ tells us the map object does not have a length, and therefore len() is an illegal operation for the float object.

Retrieving the length of an object is only suitable for iterable objects, like a list or a tuple.

A floating point is a real number, that can be positive or negative with a fractional component after a decimal point.

The len() method implicitly calls the dunder method __len__() which returns a positive integer representing the length of the object on which it is called. All iterable objects have __len__ as an attribute. Let’s check if __len__ is in the list of attributes for an float object and a list object using the built-in dir() method.

my_float = 4.3

print(type(my_float))

print('__len__' in dir(my_float))
<class 'float'>
False

We can see that __len__ is not present in the attributes of the int object.

lst = ["football", "rugby", "tennis"]

print(type(lst))

print('__len__' in dir(lst))
<class 'list'>
True

We can see that __len__ is present in the attributes of the list object.

Example

Let’s look at an example of trying to get the length of an float object. First, we will define a function that counts the number of pizzas sold by a pizzeria.

def get_total_pizza(pizza_dict):

    pizza_count = sum(pizza_dict.values())

    print(f'Number of pizzas sold: {len(pizza_count)}')

The function takes a Python dictionary and returns the sum of its values.

Next, we will define a dictionary containing key-value pairs of pizzas and the amount sold.

pizza_dict={'margherita':8.5, 'pepperoni':4.5, 'hawaiian':10, 'marinara':3.75}

Next, we will pass the dictionary as the argument for the get_total_pizza() call to get the total number of pizzas sold.

get_total_pizza(pizza_dict)

Let’s run the code to get the result:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [46], in <cell line: 1>()
----> 1 get_total_pizza(pizza_dict)

Input In [44], in get_total_pizza(pizza_dict)
      1 def get_total_pizza(pizza_dict):
      3     pizza_count = sum(pizza_dict.values())
----> 5     print(f'Number of pizzas sold: {len(pizza_count)}')

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

The error occurs because pizza_count is a float. The sum() function returns a float. Therefore, when we try to get the length of pizza_count using len(), we are trying to get the length of a float.

We can check the type of an object using the built-in type() function.

pizza_dict={'margherita':8.5, 'pepperoni':4.5, 'hawaiian':10, 'marinara':3.75}

pizza_count = sum(pizza_dict.values())

print(type(pizza_count))
<class 'float'>

Solution

We can solve this error by removing the len() function call in the print statement. Let’s look at the revised code:

def get_total_pizza(pizza_dict):

    pizza_count = sum(pizza_dict.values())

    print(f'Number of pizzas sold: {pizza_count}')


pizza_dict={'margherita':8.5, 'pepperoni':4.5, 'hawaiian':10, 'marinara':3.75}

get_total_pizza(pizza_dict)

Let’s run the code to get the total number of pizzas sold:

Number of pizzas sold: 26.75

Summary

Congratulations on reading to the end of this tutorial!

For further reading on the has no len() TypeErrors, go to the article:

To learn more about Python for data science and machine learning, go to the online courses page on Python, which provides the best, easy-to-use online courses.

Research Scientist at Moogsoft | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!