How to Fix: TypeError: ‘int’ object is not iterable

3D illustration of a machine failing to unpack a solid steel block, representing the 'int object is not iterable' TypeError.

“Iterable” means “capable of being returned one at a time”. Lists, strings, and ranges are iterable. A single number (integer) is not, which is why you might encounter the error “TypeError int object is not iterable” when trying to iterate over an integer.

The Cause

You tried to loop over a number directly.

Problem Code:

n = 5
for i in n:  # CRASH! You can't loop THROUGH the number 5.
    print("Hello")

The Fix: Use range()

If you want to loop n times, you must use the range() function.

n = 5
for i in range(n):  # Correct! range(5) creates [0, 1, 2, 3, 4]
    print("Hello")

Another Common Scenario

Sometimes you accidentally overwrite a list with a number.

numbers = [1, 2, 3]
# ... later in code ...
numbers = 100  # Oops, we overwrote the list!

for num in numbers: # CRASH!
    print(num)

Always be careful when reusing variable names!

Similar Posts

Leave a Reply