Last updated: Apr 20, 2022
Photo from Unsplash
The Python "TypeError: object of type 'int' has no len()" occurs when we pass
an integer to the
len() function. To solve the error, convert the integer to a
len(str(my_int)) or correct the assignment and pass a sequence
str, etc) to the
Here is an example of how the error occurs.
my_int = 100 # ⛔️ TypeError: object of type 'int' has no len() print(len(my_int))
We passed an integer to the
len() function which caused the error.
If you need to get the length of an integer, convert it to a string first.
my_int = 100 print(len(str(my_int))) # 👉️ 3
The len() function returns the length (the number of items) of an object.
my_list = ['apple', 'banana', 'kiwi'] result = len(my_list) print(result) # 👉️ 3
Notice that the
len() function cannot be called with an integer.
If you didn't expect the variable to store an integer value, you have to correct the assignment.
If you are trying to iterate a specific number of times, use the
my_int = 5 for n in range(my_int): print(n) result = list(range(my_int)) # 👇️ [0, 1, 2, 3, 4] print(result)
The range class is
commonly used for looping a specific number of times in
for loops and takes
the following parameters:
|An integer representing the start of the range (defaults to |
|Go up to, but not including the provided integer|
|Range will consist of every N numbers from |
You can use the
dir() function to print an object's attributes and look for
my_int = 5 print(dir(my_int))
Or you can check using a
my_int = 5 try: print(my_int.__len__) except AttributeError: # 👇️ this runs print('object has no attribute __len__')
We try to access the object's
__len__ attribute in the
try block and if an
AttributeError is raised, we know the object doesn't have a
attribute and cannot be passed to the
If you aren't sure what type a variable stores, use the built-in
my_int = 5 print(type(my_int)) # 👉️ <class 'int'> print(isinstance(my_int, int)) # 👉️ True
The type class returns the type of an object.
True if the passed in object is an instance or a subclass of
the passed in class.