The error message:
TypeError: argument of type 'int' is not iterable
occurs when you try to use an integer (int
) in a context where an iterable (like a list, tuple, string, or dictionary) is expected.
1. Causes and Solutions
Cause 1: Using in
Operator on an Integer
The in
operator checks if a value exists inside an iterable, but if the object is an integer, Python raises this error.
Incorrect Code:
num = 100
if 5 in num: # TypeError
print("Found!")
Solution: Convert num
to a String or Iterable
num = "100"
if "5" in num: # Now it's iterable
print("Found!")
OR
digits = [1, 0, 0]
if 5 in digits: # Checking inside a list
print("Found!")
Cause 2: Checking Membership in an Integer Instead of a List or String
Trying to check if a number exists inside another number using in
leads to this error.
Incorrect Code:
number = 12345
if 2 in number: # TypeError
print("Found!")
Solution: Convert to String or List
if "2" in str(number): # Convert to string
print("Found!") # Output: Found!
Cause 3: Iterating Over an Integer Instead of an Iterable
Looping over an integer directly is not allowed.
Incorrect Code:
num = 5
for digit in num: # TypeError
print(digit)
Solution: Convert to a String or Use range()
for digit in str(num): # Convert to string
print(digit) # Output: 5
OR
for i in range(num): # Works correctly
print(i)
Cause 4: Using int
Instead of list
in Functions That Expect an Iterable
Functions like sum()
, max()
, min()
, and sorted()
expect an iterable as input.
Incorrect Code:
num = 1234
print(sum(num)) # TypeError
Solution: Convert to a List of Digits
num_list = [int(digit) for digit in str(num)] # Convert digits into a list
print(sum(num_list)) # Output: 10 (1+2+3+4)
Cause 5: Passing an Integer Instead of a List or String to Functions
Some functions require an iterable, but if an integer is passed instead, Python raises this error.
Incorrect Code:
len(12345) # TypeError: int is not iterable
Solution: Convert to String
print(len(str(12345))) # Output: 5