Last modified: Apr 09, 2025 By Alexander Williams

Fix TypeError: 'int' has no len() in Python

Python's len() function is used to get the length of sequences. But it doesn't work with integers. This article explains why and how to fix it.

What Causes This Error?

The error occurs when you try to use len() on an integer. Integers don't have a length property like strings or lists.


# This will cause the error
num = 42
print(len(num))


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

Common Scenarios

This error often happens when:

1. You forget to convert an integer to a string first.

2. You mix up variable types in your code.

3. You assume a function returns a sequence when it returns a number.

How To Fix It

The solution depends on what you're trying to do. Here are common fixes:

1. Convert to String First

If you need the digit count, convert the number to a string first:


num = 42
print(len(str(num)))  # Convert to string first


2

2. Check Variable Type

Use type() to verify your variable is what you expect:


value = 42
if isinstance(value, (str, list, dict)):
    print(len(value))
else:
    print("Value is not a sequence")


Value is not a sequence

3. Fix Function Return Types

Make sure functions return the expected type. Document return types clearly.

Prevention Tips

Follow these practices to avoid this error:

1. Always check variable types before using len().

2. Use type hints in your functions.

3. Write tests that verify function return types.

Similar type-related errors include AttributeError and TypeError for other operations. For module issues, see this guide.

Conclusion

The 'int' has no len() error is easy to fix once you understand it. Always verify your variable types before using len(). Convert numbers to strings if you need digit counts.

Remember, Python is strict about types. Being careful with variable types will prevent many common errors.