How to Fix the TypeError: Int Object Is Not Iterable Error in Python

Rohan Timalsina Feb 15, 2024
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:

check if the object is iterable in python

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.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - Python Error