The error message:
TypeError: 'int' object is not iterable
occurs when you try to iterate over an integer (int
), but Python expects an iterable (like a list, tuple, set, or string).
1. Causes and Solutions
Cause 1: Using a for
Loop on an Integer
A for
loop requires an iterable, but an integer is not iterable.
Incorrect Code:
num = 5
for i in num: # TypeError: 'int' object is not iterable
print(i)
Solution: Use range()
to Make it Iterable
num = 5
for i in range(num): # Works fine
print(i) # Output: 0, 1, 2, 3, 4
Cause 2: Passing an Integer Where an Iterable is Expected
Some built-in functions like sum()
, max()
, or min()
expect an iterable.
Incorrect Code:
print(sum(100)) # TypeError: 'int' object is not iterable
Solution: Convert the Integer to an Iterable (List, Tuple, etc.)
print(sum([100])) # Works fine, Output: 100
Cause 3: Assigning an Integer Instead of a List or Tuple
If a function expects a list but receives an integer, a TypeError
occurs.
Incorrect Code:
def double_numbers(nums):
return [n * 2 for n in nums] # Expecting an iterable
print(double_numbers(5)) # TypeError
Solution: Pass a List Instead of an Integer
print(double_numbers([5])) # Works fine, Output: [10]
Cause 4: Unpacking an Integer
Unpacking requires an iterable, but an integer cannot be unpacked.
Incorrect Code:
a, b = 10 # TypeError: 'int' object is not iterable
Solution: Use a Tuple or List
a, b = (10, 20) # Works fine
print(a, b) # Output: 10 20