TypeError: 'int' object is not iterable
What it means
Python expected something it could go through one item at a time, such as a list, a string or a range, and got a single number. A for loop, sum(), max() and list() all need a collection, not one number.
1. Looping over a number instead of a range
This raises the error
Broken
times = 3
for i in times:
print("Hello", i)
Output
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: 'int' object is not iterable
The fix
Fixed
times = 3
for i in range(times):
print("Hello", i)
Output
Hello 0 Hello 1 Hello 2
range(3) gives the numbers 0, 1 and 2, so the loop runs 3 times. The number 3 on its own has nothing to loop over.
2. Looping over `len()` of a list
This raises the error
Broken
names = ["Ada", "Alan", "Grace"]
for i in len(names):
print(i, names[i])
Output
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: 'int' object is not iterable
The fix
Fixed
names = ["Ada", "Alan", "Grace"]
for i, name in enumerate(names):
print(i, name)
Output
0 Ada 1 Alan 2 Grace
len(names) is the single number 3. enumerate() gives each position together with its item. range(len(names)) also works.
3. Adding up the digits of a number with `sum()`
This raises the error
Broken
n = 1234
print(sum(n))
Output
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: 'int' object is not iterable
The fix
Fixed
n = 1234
print(sum(int(d) for d in str(n)))
Output
10
A number has no digits to loop over, but its string does. Each character goes back to a number with int() before adding.
When you see this error, check
- To repeat something
ntimes, loop overrange(n). - Loop over the list itself, or
enumerate(list), instead oflen(list). - Print the value and its
type()just before the loop. - For digits, turn the number into a string first:
str(n).
Related errors
All Python errors · How to read a traceback · Step through your code