How to Fix the TypeError: Int Object Is Not Iterable Error in Python
In Python, 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
.
The error 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.
Fix the 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))
Output:
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))
Output:
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))
Output:
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 __iter__
.
s = "apple"
print(dir(s))
Output:
The string 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.
The error 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.
Related Article - Python Error
- Can Only Concatenate List (Not Int) to List in Python
- How to Fix Value Error Need More Than One Value to Unpack in Python
- How to Fix ValueError Arrays Must All Be the Same Length in Python
- Invalid Syntax in Python
- How to Fix the TypeError: Object of Type 'Int64' Is Not JSON Serializable
- How to Fix the TypeError: 'float' Object Cannot Be Interpreted as an Integer in Python