Python - How to solve 'int' object is not iterable
In this tutorial, we are going to learn about how to solve the TypeError: ‘int’ object is not iterable in Python.
The int
object is not iterable error occurs, when we try to iterate over a integer value using for loop, python complier throws the error.
Here is an example:
price = 434
for i in price:
print (i)
Output:
Traceback (most recent call last):
File "main.py", line 11, in <module>
for i in price:
TypeError: 'int' object is not iterable
In the example above, we are trying to iterate over a integer, but integer objects are not iterable in Python.
To solve the error, convert the integer value to a string using str()
function then iterate over it, because strings are iterable in Python.
Here is an example:
price = 434
result = str(price)
for i in result:
print (i)
Output:
4
3
4
Note: If you want convert the string to a integer back, you can use the int()
function in Python.
We can also run the for loop number of times by passing the integer value to a range()
function.
counter = 6
for i in range(counter):
print(i)
Output:
0
1
2
3
4
5
The range()
function starts from 0 and ends before the passed number.
Conclusion
The “int” object is not a iterable error occurs, when we try to iterate over the integer value as a list or string, etc. To solve the error, convert the integer to string using str()
function then iterate over it.