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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

The Python "TypeError: object of type 'function' has no len()" occurs when we pass a function without calling it to the len() function. To solve the error, make sure to call the function and pass the result to the len() function.

typeerror object of type function has no len

Here is an example of how the error occurs.

main.py
def get_list(): return ['a', 'b', 'c'] # ⛔️ TypeError: object of type 'function' has no len() print(len(get_list)) # 👈️ forgot to call function

We forgot to call the get_list function with parentheses, e.g. get_list(), so our code actually tries to get the length of a function object.

To solve the error, make sure to call the function and pass the result to the len() function.

main.py
def get_list(): return ['a', 'b', 'c'] # ✅ call get_list() print(len(get_list())) # 👉️ 3

We used parentheses to invoke the function, so the len() function now gets called with a list and not a function object.

The len() function returns the length (the number of items) of an object.

main.py
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).

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

main.py
my_list = ['a', 'b', 'c'] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ True def get_list(): return ['a', 'b', 'c'] print(type(get_list)) # 👉️ <class 'function'> print(callable(get_list)) # 👉️ 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.

The callable function takes an object as an argument and returns True if the object appears callable, otherwise False is returned.

If the callable() function returns True, it is still possible that calling the object fails, however if it returns False, calling the object will never succeed.

Conclusion #

The Python "TypeError: object of type 'function' has no len()" occurs when we pass a function without calling it to the len() function. To solve the error, make sure to call the function and pass the result to the len() function.

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.