Python TypeError: int object is not iterable: What To Do To Fix It?

Are you seeing the error “TypeError ‘int’ object is not iterable” while running a Python program? This tutorial will show you how to fix it.

Python raises the TypeError ‘int’ object is not iterable when you try to access a variable of type integer as an iterable. One scenario in which this might happen is if by mistake you try to iterate through an integer variable using a for loop when you actually expect it to be an iterable (e.g. a list, tuple, or set).

I will show you an example of code that causes this error and then we will fix it together!

You will also learn how to troubleshoot a more complex example at the end of the article.

What Does the Python TypeError “int object is not iterable” Mean?

An iterable in Python is an object you can iterate through. Some examples of iterables are lists, tuples, and sets.

The most common way to iterate through an iterable is by using a Python for loop, but sometimes this can lead to a TypeError due to mistakes in the code.

Let’s have a look at the following Python code:

numbers = [3, 56, 78, 65, 5, 3]

for number in len(numbers):
    print(number)

If you look at this code quickly you might not see any errors straight away.

When executing the code you will see the following error:

Traceback (most recent call last):
  File "/opt/codefathertech/tutorials/list_iterator.py", line 3, in <module>
    for number in len(numbers):
TypeError: 'int' object is not iterable

Why this error message?

The cause of this error is the fact that we are using a for loop to iterate through the variable with value len(numbers) and this variable is an integer that contains the number of elements in the list numbers.

The initial intent of the code was to loop through each element in the list and if we wrote the code correctly it would work as expected because a list is an iterable.

What change do you have to make to the code to make it work?

To fix the TypeError “int object is not iterable” use the range function on the first line of the for loop.

for number in len(numbers):

becomes:

for number in range(len(numbers)):

Let’s have a look at the updated code:

numbers = [3, 56, 78, 65, 5, 3]

for number in range(len(numbers)):
    print(number)

Execute the code to confirm that you stop seeing the TypeError and that all the numbers in the list are printed in the output correctly.

0
1
2
3
4
5

All good! You fixed this error.

Note: the code that is raising this exception in your case might be slightly different from the example we have seen. The main point is for you to check if by mistake you are trying to loop through an integer.

How Can You Make an Integer Value Iterable in Python?

An integer represents a single value and it’s conceptually incorrect trying to loop over it. Integers are not iterable.

It doesn’t really make sense to make an integer iterable considering that an iterable is a Python object that contains multiple objects (e.g. a list that contains multiple strings you can loop through).

How Do You Check if an Object is Iterable in Python?

An iterable object in Python implements the method __iter__() so a simple way to check if an object is an iterable is to verify if the object has the method __iter__().

Let’s take as an example one list and one integer to show how the first implements the __iter__() method while the second one doesn’t.

To verify if the __iter__() method is present in the object you can use the built-in function hasattr().

Checking if a list is iterable

numbers = [3, 56, 78, 65, 5, 3]

if hasattr(numbers, '__iter__'):
    print("This object is iterable")
else:
    print("This object is not iterable")

[output]
This object is iterable

This code confirms that a list is iterable.

Using the Python dir() function you can also see that this list has the method __iter__():

numbers = [3, 56, 78, 65, 5, 3]
print(dir(numbers))

[output]
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Checking if an integer is iterable

number = 3

if hasattr(number, '__iter__'):
    print("This object is iterable")
else:
    print("This object is not iterable")

[output]
This object is not iterable

By calling the dir() function you can also see that an integer does not have the method __iter__():

number = 3
print(dir(number))

[output]
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

Go through the output of the dir() function in both cases and make sure you understand the difference (the __iter__() method is only present in a list and not in an integer).

Example on How to Fix TypeError: int object is not iterable

Conceptually you now know why this exception is raised in Python.

At the same time, depending on the complexity of the code, it might be a bit harder to understand the root cause of the error.

Let’s take as an example the following code that is supposed to increase each number in a matrix by one and then print all the numbers in the matrix.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for row in matrix:
    for column in range(len(row)):
        matrix[column] += 1

print(matrix)

From a first look, this code might seem correct.

So, let’s try to execute it:

Traceback (most recent call last):
  File "/opt/codefathertech/tutorials/list_iterator.py", line 5, in <module>
    matrix[column] += 1
TypeError: 'int' object is not iterable

The TypeError is complaining about the following line of code:

matrix[column] += 1

But why?

That’s because when using the += operator with a list you also need a list on the right side of the operator while in this code on the right side of the operator, we have an integer.

Also, the real problem here is that we have a conceptual bug in the code considering that the original intention of this code is to increment each number in the matrix by 1.

Let’s update our code to do that:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for row in matrix:
    for column in range(len(row)):
        row[column] += 1

print(matrix)

And the output is:

[[2, 3, 4], [5, 6, 7], [8, 9, 10]]

That’s correct!

Conclusion

In this Python tutorial, you learned to troubleshoot the error “TypeError: ‘int’ object is not iterable” and to identify which part of the code causes it.

We went through a few examples including a more complex one that shows that sometimes is not always easy to understand why this error occurs and how to fix it.

By practicing your Python coding you will find it easier to identify and address this type of error.

Related article: would you like to feel more confident about your Python knowledge? Start building a strong Python foundation with this Python specialization.

Leave a Comment