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


Borislav Hadzhiev

Last updated: Apr 20, 2022


Photo from Unsplash

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

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 string, e.g. len(str(my_int)) or correct the assignment and pass a sequence (list, str, etc) to the len() function.

typeerror object of type int has no len

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

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 range() class.

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:

startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

Note that when we pass an object to the len() function, the object's __len__() method is called.

You can use the dir() function to print an object's attributes and look for the __len__ attribute.

my_int = 5 print(dir(my_int))

Or you can check using a try/except statement.

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 __len__ attribute and cannot be passed to the len() function.

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

my_int = 5 print(type(my_int)) # 👉️ <class 'int'> print(isinstance(my_int, int)) # 👉️ 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.

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.