The error "TypeError: 'int' object is not iterable" occurs in Python when you try to iterate over an integer as if it were a list, tuple, or another iterable object. This can happen in several scenarios, but here are the most common cases and how to fix them:

1. Looping Over an Integer

Problem: You might have written a loop that mistakenly tries to iterate over an integer.

Example:

num = 5
for i in num:
    print(i)
  • Error: The above code throws TypeError: 'int' object is not iterable because num is an integer.

Solution: If you want to iterate num times, use the range() function.

num = 5
for i in range(num):
    print(i)

2. Unpacking Values

Problem: When trying to unpack or iterate over what is expected to be an iterable, but it turns out to be an integer.

Example:

a, b = 5
  • Error: This will throw a TypeError because 5 is an integer and cannot be unpacked into multiple variables.

Solution: Make sure the value you’re unpacking is an iterable like a tuple, list, or string.

a, b = (5, 6)

3. Using Functions That Return Integers Instead of Iterables

Problem: You might be using a function that returns an integer but you mistakenly assume it returns an iterable.

Example:

def get_number():
    return 5

for i in get_number():
    print(i)
  • Error: The function get_number() returns an integer, so the loop will raise a TypeError.

Solution: Modify the function or your code to ensure the function returns an iterable if you intend to loop through it.

def get_numbers():
    return [5, 6, 7]

for i in get_numbers():
    print(i)

4. Passing Integers to Functions Expecting Iterables

Problem: Passing an integer to a function that expects an iterable (like list() or sum()).

Example:

sum(5)
  • Error: This will throw a TypeError because sum() expects an iterable.

Solution: If you're trying to sum up numbers, put them in a list or another iterable structure.

sum([5])

Summary:

Always ensure that the variable or value you're trying to iterate over is an iterable object like a list, tuple, string, or dictionary. If you intend to perform operations multiple times, consider using the range() function or ensure that functions return iterables when necessary.

Simon

102 Articles

I love talking about tech.