Editor

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.

Try fixing it yourself in the editor

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.

Try fixing it yourself in the editor

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.

Try fixing it yourself in the editor

When you see this error, check

  • To repeat something n times, loop over range(n).
  • Loop over the list itself, or enumerate(list), instead of len(list).
  • Print the value and its type() just before the loop.
  • For digits, turn the number into a string first: str(n).

All Python errors · How to read a traceback · Step through your code