Register Login

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

Updated May 03, 2020

In this article, we will learn about the TypeError: object of type ‘int’ has no len.

What is TypeError: object of type ‘int’ has no len?

This error is generated when we try to calculate the length of an integer value. But integer don’t have any length. Thus the error is raised.

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

Let us understand it more with the help of an example.

Example

# Importing random module
import random 

# Using randit function of random module
var = random.randint(0, 20)

# Printing Random value
print("Random value: ",var)

# Printing length of variable
print("Length of variable: ",len(var))

Output

Random value:  18
  File "len.py", line 12, in <module>
    print("Length of variable: ",len(var))
TypeError: object of type 'int' has no len()

Explanation

In the above example, we imported the random module of python. There are various function available in random module of python. In this particular code, we used the randint() function. This function returns any random integer within the specified parameter value.

After generating the random integer we stored it in the variable ‘var’. And printed it in the next line. There’s no error encountered until now. But when we try to try to calculate the length of the variable var’ in line-12 of the code. An error is encountered. This TypeError is raised because we were trying to calculate the length of an integer. And we know integers don’t have any length.

Solution

# Importing random module
import random 

# Using randit(start,end) function of random module
var = random.randint(0, 20)

# Printing Random value
print("Random value: ",var)

# Printing length of variable
print("Length of variable: ",len(str(var))) 

Output

Random value:  2
Length of variable:  1

Explanation

As discussed earlier we can not calculate the length of an integer. But we can calculate the length of the string. So what we can do is, change the integer value to the string. And then calculate the length of that string.

Here we used a built-in function str() to change varto string.

Conclusion

This TypeError is raised when we try to calculate the length of an integer using len(). To work around this error we can convert the integer value to string. And then calculate the length of the string.


×