Solutions For TypeError: ‘int’ object is not iterable in Python

TypeError: ‘int’ object is not iterable in Python occurs when we pass an integer object into the loop. To fix it, you can use the range() function to make the loop run or check the value’s data type before looping. This article will give examples and solutions for it. Let’s get started.

Cause of TypeError: ‘int’ object is not iterable in Python.

Python loops need to iterate over iterable objects such as Lists, Dictionaries, etc. The cause of Error is that you loop over an integer object. This Error may appear in the following cases.

Error Example:

price = 250

# Error occurred when passing an integer variable to the loop
for i in price:
    print(i)

Output:

TypeError: 'int' object is not iterable

Errors can also occur when you get a value from input() function and loop on it.

Error Example:

# Enter the number of items in the cart
cart = int(input("How many items in the cart?"))
count = 0

# Execute loop on an integer variable
for i in cart:
    count = count + 1

print(count)

Output:

TypeError: 'int' object is not iterable

How to fix TypeError: ‘int’ object is not iterable in Python.

You need to add the range() function into the loop to solve this Error. This function will generate a list of numbers so the for loop can iterate over it.

Use range() function

Example of correct code:

# Suppose enter 10 in the cart
cart = int(input("How many items are in the cart? "))
count = 0

# Use the range() function so the for loop can run
for i in range(cart):
    count = count + 1

print(f"There are {count} items in the cart")

Output:

How many items are in the cart? 10
There are 10 items in the cart

Use dir() to check the value.

To avoid errors, you can check the variable’s value before putting it in the loop. You can use the dir() function. If you see __iter__ appear, it means the variable is iterable.

Example:

fruits = ["apple", "banana", "cherry"]

# Use dir() to check the variable's method
print(dir(fruits))

Output:

['__add__', '__contains__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce_ex__', '__repr__', '__rmul__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'count', 'extend', 'insert', 'pop', 'reverse', 'sort']

We have seen __iter__ in the output, proving this variable is iterable.

Summary

Through the article, we have understood a standard error in Python. The easiest way to fix it is to use the range() function to make the loop run. Thank you for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *