Last modified: Apr 09, 2025 By Alexander Williams
Fix TypeError: 'function' has no len() in Python
Getting a TypeError: object of type 'function' has no len()? This error occurs when you try to use the len()
function on a Python function. Let's explore why this happens and how to fix it.
Table Of Contents
What Causes This Error?
The error means you're trying to get the length of a function object. The len()
function only works on sequences or collections like lists, strings, or dictionaries.
Here's a common example that triggers this error:
def my_function():
return "Hello"
print(len(my_function)) # Wrong: passing the function itself
TypeError: object of type 'function' has no len()
How To Solve The Error
The solution is simple: call the function first, then use len()
on its return value. Here's the corrected version:
def my_function():
return "Hello"
print(len(my_function())) # Correct: passing the function's return value
5
Common Scenarios
This error often occurs in these situations:
1. Forgetting parentheses when calling a function
2. Passing a function as argument without calling it
3. Confusing function objects with their return values
Example With Lists
Here's another example showing the right and wrong ways:
def get_list():
return [1, 2, 3]
# Wrong way:
print(len(get_list)) # Error
# Right way:
print(len(get_list())) # Outputs 3
Debugging Tips
When you see this error:
1. Check where you're using len()
2. Verify you're calling the function with ()
3. Print the object type using type()
For more Python debugging, see our guide on solving ModuleNotFoundError.
Conclusion
The TypeError: object of type 'function' has no len() is easy to fix. Always remember to call functions before using len()
. This ensures you're measuring the return value, not the function itself.
With these examples and tips, you should now understand and resolve this common Python error. Happy coding!