This error occurs when you try to iterate over an integer in Python. To fix this, make sure anything after the in
operator in Python is an iterable, such as a list. If you’re trying to use the integer to determine the number of times you’d like a for
loop to run, use the range()
function on it to produce a list of the numbers you want to iterate over.
Table of Contents
Problem: you are using an integer in a for loop
The most common cause of this error is trying to use an integer directly after the in
operator in a for
loop.
Check out the example below:
foo = 3
for i in foo:
print(i)
PythonWe define a variable foo
and assign the value 3
to it. Then, we try to iterate over it, which causes the following error:
Traceback (most recent call last):
File "/home/user/main.py", line 3, in <module>
for i in foo:
TypeError: 'int' object is not iterable
This is happening because in
expects an iterable. You’re probably trying to run the loop foo
times, and instead of passing a range of numbers to iterate over, you passed just the number instead. Luckily this is very easy to fix!
Solution: use the range function to make it iterable
Python has a built in function that does exactly what you need. All you have to do to fix the above example is call the range
function on foo
and you’re good to go:
foo = 3
for i in range(foo):
print(i)
PythonThe output, as expected, will give you a range of numbers starting with zero, up to but not including the value you called range
on. Below is the output:
0
1
2
It’s for this reason range
is frequently used in for
loops to set how many times the loop will run.
And just in case you were curious, the range
function does not return a list
, it actually returns a range
object, so range()
, while it is a function, is also a constructor that returns an object:
>>> type(range(2))
<class 'range'>
PythonConclusion
The Python error “TypeError: ‘int’ object is not iterable” means you tried to iterate over an integer. The best way to fix this, if you’re trying to use it as the number of times you want a for
loop to run, is to use the range()
function to turn that integer into an iterable.
John is a professional software engineer who has been solving problems with code for 15+ years. He has experience with full stack web development, container orchestration, mobile development, DevOps, Windows and Linux kernel development, cybersecurity, and reverse engineering. In his spare time, he’s researching the potential business applications of AI.