In python, the error “TypeError: object of type ‘int’ has no len()” occurs when the length function is invoked on objects that does not support the length function. The length function is supported by iterable objects such as list, tuple, dictionary and string.
The length function is used to find the length of the string or the number of objects in a structured objects such as list, tuple and dictionary. The length function does not supported by the data types such as int, float, long, boolean, complex data types. If the length function is invoked on unsupported objects, the python interpreter will cause the error.
The purpose of the len() function is to determine the length of the list, tuple, dictation, or string. In this article, we can see what this error is, how this error can be resolved. The error would be thrown as like below.
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
print (len(s))
TypeError: object of type 'int' has no len()
[Finished in 0.2s with exit code 1]
Different Variation of the error
In different contexts the “TypeError: object of type ‘int’ has no len()” error is thrown in various forms in python. The numerous variations of TypeError are shown below.
TypeError: object of type 'NoneType' has no len()
TypeError: object of type 'int' has no len()
TypeError: object of type 'float' has no len()
TypeError: object of type 'long' has no len()
TypeError: object of type 'bool' has no len()
TypeError: object of type 'complex' has no len()
TypeError: object of type 'type' has no len()
TypeError: object of type 'builtin_function_or_method' has no len()
Root Cause
The root cause of this error is that the len() function is invoked on objects that are not supported to calculate the length. Iterable objects such as list, tuple, dictionary, and strings are supported to find the length of the elements in it.
The len() function does not make sense for types such as integer, float, boolean, long, complex. The Python interpreter will throw this error when the len() function is invoked on this.
How to reproduce this error
If the len() function is invoked for the unsupported objects such as int, float, boolean, long etc, this error will be thrown. calling the len() function for the unsupported objects to reproduce this error “TypeError: object of type ‘int’ has no len()” in python.
s=5
print (len(s))
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
print (len(s))
TypeError: object of type 'int' has no len()
[Finished in 0.2s with exit code 1]
Solution 1
The len() function should only be used for iterable objects such as list, tuple, dictionary and string. Make sure you return any of the objects. Changing the primary data types to the iterable objects will resolve this error “TypeError: object of type ‘int’ has no len()” in python.
s = [5,4]
print (len(s))
Output
2
Solution 2
The len() function must be called before checking the object type. If the object is an iterable object, such as a list, tuple, dictionary, or string, the len() function will be called. Otherwise the error message “TypeError: object of type ‘int’ has no len()” will be shown to the user that the length of the object can not be found.
s=[2]
print type(s)
if type(s) in (list,tuple,dict, str):
print (len(s))
else:
print "not a list"
Output
1
Solution 3
The length can not be determined if the argument for the len() function is None. The value of the argument must be checked for non-None before calling the len() function. The error message “TypeError: object of type ‘NoneType’ has no len()” will be shown as in the example below.
s=None
print (len(s))
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
print (len(s))
TypeError: object of type 'NoneType' has no len()
[Finished in 0.1s with exit code 1]
Solution
s=None
print type(s)
if s is None :
print "a None value"
else:
print (len(s))
Output
a None value
Solution 4
The length can not be determined if the argument for the len() function is a python type. The value of the argument must be checked for type before calling the len() function or default value is set. The error message “TypeError: object of type ‘type’ has no len()” will be shown as in the example below.
s=list
print len(s)
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
print len(s)
TypeError: object of type 'type' has no len()
[Finished in 0.0s with exit code 1]
Solution
s=list()
print len(s)
Output
0
Solution 5
The length can not be determined if the argument for the len() function is a python build in function. The value of the argument must be checked before calling the len() function. The error message will be shown as in the example below.
s=len
print len(s)
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
print len(s)
TypeError: object of type 'builtin_function_or_method' has no len()
[Finished in 0.1s with exit code 1]
Solution
s=(2,3)
print len(s)
Output
2
I have seen this data type error come up numerous times while working on my data analytics projects, and recently decided to investigate further. On initial inspection, it can seem a bit of a funny one, but in actual fact, it is quite straight forward.
Lets break it down and see what is going on
So in the below code, there are a number of things:
On line 1 we have a variable that is an integer. If we think about this logically, something that is a single numeric number cannot have a length.
An integer by design is purely to count up a number of apples or no of people, it cannot be viewed as having a length as it is descriptive of the number of occurrences of an object.
data = 100
print(type(data))
print(len(data))
Output Error:
<class 'int'>
Traceback (most recent call last):
File "object of type int.py", line 3, in <module>
print(len(data))
TypeError: object of type 'int' has no len()
So for it to in anyway allow a length to be calculated, the object needs to be one of the following data types:
- List
- String
- Tuple
- Dictionary
Opposite to an integer, these are datatypes that have values that would be more appropriate to having values that a length can be calculated on.
data = "100"
print(type(data))
print("Length of string is: ", len(data))
data = [100,200,300]
print(type(data))
print("Length of list is: ", len(data))
data = (100,200,300)
print(type(data))
print("Length of tuple is: ", len(data))
data = {"Age": 1, "Name": 2}
print(type(data))
print("Length of dictionary is: ", len(data))
And the output is:
<class 'str'>
Length of string is: 3
<class 'list'>
Length of list is: 3
<class 'tuple'>
Length of tuple is: 3
<class 'dict'>
Length of dictionary is: 2
In summary, to understand this error and fix it:
An integer describes the number of things that exist for an object, they are actually not the actual object in existence.
Anything that can have a length method applied to it actually exists and can be counted. In the above four examples, they are actually values that you could describe as existing as you can count each one of them.
The explanation here hopefully clears up the matter, if you have any questions leave a comment and I will answer for you!
This Python error means that you tried to call len() on an int. len() can only be called on iterables like lists or tuples. To fix this, check to make sure the object is iterable first using an if statement or wrap the len() call in a try / except block.
The built-in function len() is great. It’s used to get the length of an iterable object, which means stuff like lists, tuples, and even dicts. If you’re not familiar with the term, iterable just means something you can iterate over, i.e. count. If you can’t count it, you can’t get its len(), because, well, it doesn’t have one.
Integers fall into this category of non-iterable. This probably seems counterintuitive… more on that later. Let’s dive into the problem!
❌ Problem: you called len() on an int
ints don’t have a len(). You might think they should, but they don’t.
Why can’t I take the length of an int? Shouldn’t it be whatever number it represents?
This is a common sticking point for new programmers. Integers might, on the surface, appear to have a length. But think about it for a second. If you have a variable that is supposed to represent the length of something, like a variable called “centimeters”, you’d think taking the len() of that variable would just give you the number of centimeters stored in it. But that’s not going to work from a language design perspective, because Python has no idea, and doesn’t even care, what the number in the variable named “centimeters” means. It’s a value not a length.
What if you were to ask, “what’s the length of 5”? There’s no answer to that, because 5 is just a number. It could be 1, because there’s one number, or it could be 5 because it represents a length already. See what I mean? Python doesn’t know and doesn’t care. It can only get the len() of something that can be counted, i.e. an iterable.
Example
Here’s some code that’ll trigger the error:
If you try to run this, you’ll get the following error message:
Traceback (most recent call last):
File "/home/user/main.py", line 2, in <module>
print(len(foo))
TypeError: object of type 'int' has no len()
Yep, just as we expected. Can’t do that. So what do we do about it?
✅ Fix 1: ensure the object implements __len__ before taking the len()
There’s a trick in Python to make sure an object is iterable (i.e., countable) before you try to get its length. That trick lies in the built-in function hasattr(). It’s a way to check an object has an attribute before using it. All len()-able objects in Python have the attribute __len__. Those double-underscore attributes in Python are special in that the Python language as a whole treats them differently. In fact, you could implement the __len__() method in any class and be able to get its len()!
Here’s how you’d check to make sure you have an object that implements __len__ before calling len() on it:
foo = 5
if hasattr(foo, "__len__"):
print(len(foo))
else:
print("Oh no! Foo is has no len!")
Which gives us:
Nice!
✅ Fix 2: Use a try / except block
Rather than checking first, if you’re not expecting a non-iterable to be passed to len() but still don’t want your program to crash because of it, you can use a try / except block. This way, you can print out an error message and just keep on keepin’ on instead of dumping an ugly stack trace for your users.
Here’s an example of using a try / except block to catch this error:
foo = 5
try:
print(len(foo))
except TypeError:
print("Whoops, can't take the len() of that!")
In the above code, we simply wrapped the len() function call in a try / except block in order to prevent an unhandled TypeError exception from crashing our program.
Here’s the output:
Nice! Just make sure you’re not using exceptions handling as a crutch to hide a deeper logic error in your code.
Conclusion
Now we know what causes “TypeError: object of type ‘int’ has no len()” and how we can go about fixing it. Basically, it’s caused by trying to get the len() of an integer. Which you can’t do. The possible fixes for it are:
- Check to make sure the object is iterable first with
hasattr(obj, "__len__") - Wrap the
len()call in atry/exceptblock to catch theTypeError
And that’s all there is to it. Hope this helps!