TypeError is raised when you use an object of the wrong data type in an operation or a function. For example, adding a string and integer will result in a
TypeError: 'int' object is not iterable occurs if you are trying to loop through an integer that is not iterable. The iterable objects in Python are lists, tuples, dictionaries, and sets.
This tutorial will teach you to fix the
TypeError: 'int' object is not iterable error in Python.
TypeError: Int Object Is Not Iterable Error in Python
Let’s see an example of a
TypeError exception in Python.
s="apple" counter = 0 for i in len(s): if i in ('a','e','i','o','u'): counter += 1 print("No. of vowels:" + str(counter))
Traceback (most recent call last): File "c:\Users\rhntm\myscript.py", line 3, in <module> for i in len(s): TypeError: 'int' object is not iterable
The exception is raised at line 3 in code
for i in len(s) because
len() returns an integer value (the length of the given string). The
int object is not iterable in Python, so you cannot use the
for loop through an integer.
To fix this error, you must ensure the loop iterates over an iterable object. You can remove the
len() function and iterate through a string.
s="apple" counter = 0 for i in s: if i in ('a','e','i','o','u'): counter += 1 print("No. of vowels:" + str(counter))
Number of vowels:2
Or, you can also use the
enumerate() function to iterate over characters of a string.
counter = 0 s="apple" for i, v in enumerate(s): if v in ('a','e','i','o','u'): counter += 1 print("No. of vowels:" + str(counter))
Number of vowels:2
You can check whether the object is iterable or not using the
dir() function. The object is iterable if the output contains the magic method
s is iterable.
TypeError is one of the common errors in Python. It occurs when you perform an operation or function with an object of the wrong data type.
int object is not iterable is raised when you iterate over an integer data type. Now you should know how to solve this problem in Python.