I am having a list with int values, iterating the same list with a loop, while iterating it I want to check the list, with some if condition, but am getting this issue:
TypeError: argument of type 'int' is not iterable
My code:
list_b=[1,2,3,4,5,6,7,8,9] #list with int values
for m in list_b: #storing the list in m
print(m) #printing the m
for m in list_b: # again storing the same list in m
if(10 in m): #checking for presance of 10 in the list
print('yes 10 is presant in listb')
else:
print('10 is not presant in list_b')
Tomerikoo
17.6k16 gold badges39 silver badges58 bronze badges
asked Aug 20, 2019 at 17:49
![]()
3
So in is a keyword meant to iterate across an iterable data type, such as a list or string, and check if your variable is within that iterable. So you can use it like so:
ch = "cheese"
ref = "cheese, milk, eggs"
if ch in ref:
print(True)
#Prints True
or
ch = 1
l = [1,2,3,4,5]
if ch in l:
print(True)
#Prints True
But you can’t iterate across an int, it’s just one integer, so there’s the source of your error
answered Aug 20, 2019 at 17:54
![]()
2
You seem to have fundamentally misunderstood what for does. You seem to think that for m in list_b means «store list_b in m«. But what it actually means is «go through each element of list_b, and for each of them, temporarily store that value in m, and then execute the code in the for-loop». So whatever you write in the for-loop gets executes once for every element of list_b. So if you just want to print list_b and check whether 10 is in list_b, you should get rid of the for-loops:
list_b=[1,2,3,4,5,6,7,8,9] #list with int values
print(list_b) #printing the m
if(10 in list_b): #checking for presance of 10 in the list
print('' yes 10 is presant in listb')
else:
print('10 is not presant in list_b')
PS «presence» and «present» don’t have «a», they have «e».
answered Aug 20, 2019 at 18:14
AcccumulationAcccumulation
3,3931 gold badge7 silver badges12 bronze badges
1
In Python, the error TypeError: argument of type ‘int’ is not iterable occurs when the membership operator (in, not in) is used to validate the membership of a value in non iteratable objects such as list, tuple, dictionary. The membership operator can be used to verify memberships in variables such as strings, numbers, tuples and dictionary.
The membership operator (in, not in) in Python is used to test whether or not the given value exists in another variable. The operator searches the value in an iterable object. The error “TypeError: argument of type ‘int’ is not iterable” is due to the search of value in a non-iterable object.
Through this article, we can see what this error is, how this error can be solved. This type error is due to missing of an non-iterable object in the membership operator. The error would be thrown as like below.
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 3, in <module>
print x in y
TypeError: argument of type 'int' is not iterable
[Finished in 0.1s with exit code 1]
Different Variation of the error
In different contexts the “TypeError: argument of type ‘int’ is not iterable” error is thrown in various forms in python. The numerous variations of TypeError are given below.
TypeError: argument of type 'int' is not iterable
TypeError: argument of type 'float' is not iterable
TypeError: argument of type 'bool' is not iterable
TypeError: argument of type 'complex' is not iterable
TypeError: argument of type 'long' is not iterable
TypeError: argument of type 'NoneType' is not iterable
TypeError: argument of type 'type' is not iterable
Root Cause
The membership operator searches for a value in an iterable object such as list, tuple, dictionary. If the value presents in an iterable object, returns true, otherwise it returns false. If you are looking for a value in non-iterable object such as int, float, boolean, python can not identify the presents of the value. In this case the python interpreter will throw that error.
How to reproduce this issue
If you are looking for a value in non-iterable object such as int, float, boolean, the python interpreter will throw this error. The code below searches an integer value in another integer value. This error will be thrown, as an integer value is not an iterable entity.
x = 4
y = 4
print x in y
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 3, in <module>
print x in y
TypeError: argument of type 'int' is not iterable
Solution 1
If the membership operator (in, not in) is used, the value present in an iterable object such as list, tuple, or dictionary should be checked. Verify that the program looks for iterable objects. In the membership operator, the wrong variable is used, or the wrong value is given in the variable.
x = 4
y = [4, 5]
print x in y
Output
True
Solution 2
If you want to check a value with another value, you should not use the Membership Operator. Instead, the logical operator is used to compare two values. The logical operator in python will compare two values. The code below shows how to use comparison of the value.
x = 4
y = 4
print x == y
Output
True
Solution 3
If the membership operator variable contains None value, the membership operator would not be able to iterate that value. Membership operator throws “TypeError: the ‘NoneType’ argument is not iterable” error. Either Null check must be performed or assigned with an iterable object as the default.
x = 4
y = None
print x in y
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 3, in <module>
print x in y
TypeError: argument of type 'NoneType' is not iterable
Solution
x = 4
y = []
print x in y
Output
False
Solution 4
If the type of the value is used in the membership operator, python interpreter will throw “TypeError: type ‘type’ argument is not iterable” error. The value presents check can not be performed on the type of the object. It is because of error in typing. The types such as list, tuple, dict are to be modified to functions such as list(), tuple(), dict().
x = 4
y = list
print x in y
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 3, in <module>
print x in y
TypeError: argument of type 'type' is not iterable
Solution
x = 4
y = list()
print x in y
Output
False
![Int Object is Not Iterable – Python Error [Solved]](https://www.freecodecamp.org/news/content/images/size/w2000/2022/03/iterable.png)
If you are running your Python code and you see the error “TypeError: ‘int’ object is not iterable”, it means you are trying to loop through an integer or other data type that loops cannot work on.
In Python, iterable data are lists, tuples, sets, dictionaries, and so on.
In addition, this error being a “TypeError” means you’re trying to perform an operation on an inappropriate data type. For example, adding a string with an integer.
Today is the last day you should get this error while running your Python code. Because in this article, I will not just show you how to fix it, I will also show you how to check for the __iter__ magic methods so you can see if an object is iterable.
How to Fix Int Object is Not Iterable
If you are trying to loop through an integer, you will get this error:
count = 14
for i in count:
print(i)
# Output: TypeError: 'int' object is not iterable
One way to fix it is to pass the variable into the range() function.
In Python, the range function checks the variable passed into it and returns a series of numbers starting from 0 and stopping right before the specified number.
The loop will now run:
count = 14
for i in range(count):
print(i)
# Output: 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# 11
# 12
# 13
Another example that uses this solution is in the snippet below:
age = int(input("Enter your age: "))
for num in range(age):
print(num)
# Output:
# Enter your age: 6
# 0
# 1
# 2
# 3
# 4
# 5
How to Check if Data or an Object is Iterable
To check if some particular data are iterable, you can use the dir() method. If you can see the magic method __iter__, then the data are iterable. If not, then the data are not iterable and you shouldn’t bother looping through them.
perfectNum = 7
print(dir(perfectNum))
# Output:['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__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__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
The __iter__ magic method is not found in the output, so the variable perfectNum is not iterable.
jerseyNums = [43, 10, 7, 6, 8]
print(dir(jerseyNums))
# Output: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__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']
The magic method __iter__ was found, so the list jerseyNums is iterable.
Conclusion
In this article, you learned about the “Int Object is Not Iterable” error and how to fix it.
You were also able to see that it is possible to check whether an object or some data are iterable or not.
If you check for the __iter__ magic method in some data and you don’t find it, it’s better to not attempt to loop through the data at all since they’re not iterable.
Thank you for reading.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
So you’re getting the TypeError: argument of type ‘int’ is not iterable error message. I came across this issue when calling an api, extracting some data from a json object, and trying to determine if I needed to do something with that info.
Bite Size Soln for Those in a Rush
In short, you’re trying to find whether a substring exists in an integer. Make sure to cast your ints to strings and you should be able to continue on your way. Now, if you’d like a more detailed explanation, continue on.
My Setup
Python 3.x
macOS
The Issue
You are inadvertently trying to determine if a substring is in an integer! Let’s recreate it in a line or two.
word = 'stuff' blur = 12344566 word in blur
You should be greeted with the ugly, “TypeError: argument of type ‘int’ is not iterable” message.
The Solution
Cast, Cast, Cast.
word = 'stuff' blur = 12344566 word in str(blur)
A More Realistic Example
This will output false successfully telling you whether stuff can be found within the now string ‘12344566’. And now for a more realistic example.
array = ['Foo','Bar', 1]
for element in array:
print(element)
if 'sandwich' in element:
print('Found the sandwich')
Here we can see all elements of the array are printed because the error occurs on the third element. One will never find a string in an int. You can avoid checking types and error handling by wrapping element in str() to cast it as a string in case we come across any unruly data types.
array = ['Foo','Bar', 1]
for element in array:
print(element)
if 'sandwich' in str(element):
print('Found the sandwich')
The problem is gone. We also never find the sandwich. Happy coding!
Integers and iterables are distinct objects in Python. An integer stores a whole number value, and an iterable is an object capable of returning elements one at a time, for example, a list. If you try to iterate over an integer value, you will raise the error “TypeError: ‘int’ object is not iterable”. You must use an iterable when defining a for loop, for example, range(). If you use a function that requires an iterable, for example, sum(), use an iterable object as the function argument, not integer values.
This tutorial will go through the error in detail. We will go through two example scenarios and learn how to solve the error.
Table of contents
- TypeError: ‘int’ object is not iterable
- Example #1: Incorrect Use of a For Loop
- Solution
- Example #2: Invalid Sum Argument
- Solution
- Summary
TypeError: ‘int’ object is not iterable
TypeError occurs in Python when you try to perform an illegal operation for a specific data type. For example, if you try to index a floating-point number, you will raise the error: “TypeError: ‘float’ object is not subscriptable“. The part ‘int’ object is not iterable tells us the TypeError is specific to iteration. You cannot iterate over an object that is not iterable. In this case, an integer, or a floating-point number.
An iterable is a Python object that you can use as a sequence. You can go to the next item in the sequence using the next() method.
Let’s look at an example of an iterable by defining a dictionary:
d = {"two": 2, "four":4, "six": 6, "eight": 8, "ten": 10}
iterable = d.keys()
print(iterable)
dict_keys(['two', 'four', 'six', 'eight', 'ten'])
The output is the dictionary keys, which we can iterate over. You can loop over the items and get the values using a for loop:
for item in iterable:
print(d[item])
Here you use item as the index for the key in the dictionary. The following result will print to the console:
2 4 6 8 10
You can also create an iterator to use the next() method
d = {"two": 2, "four":4, "six": 6, "eight": 8, "ten": 10}
iterable = d.keys()
iterator = iter(iterable)
print(next(iterator))
print(next(iterator))
two four
The code returns the first and second items in the dictionary. Let’s look at examples of trying to iterate over an integer, which raises the error: “TypeError: ‘int’ object is not iterable”.
Example #1: Incorrect Use of a For Loop
Let’s consider a for loop where we define a variable n and assign it the value of 10. We use n as the number of loops to perform: We print each iteration as an integer in each loop.
n = 10
for i in n:
print(i)
TypeError Traceback (most recent call last)
1 for i in n:
2 print(i)
3
TypeError: 'int' object is not iterable
You raise the error because for loops are used to go across sequences. Python interpreter expects to see an iterable object, and integers are not iterable, as they cannot return items in a sequence.
Solution
You can use the range() function to solve this problem, which takes three arguments.
range(start, stop, step)
Where start is the first number from which the loop will begin, stop is the number at which the loop will end and step is how big of a jump to take from one iteration to the next. By default, start has a value of 0, and step has a value of 1. The stop parameter is compulsory.
n = 10 for i in range(n): print(i)
0 1 2 3 4 5 6 7 8 9
The code runs successfully and prints each value in the range of 0 to 9 to the console.
Example #2: Invalid Sum Argument
The sum() function returns an integer value and takes at most two arguments. The first argument must be an iterable object, and the second argument is optional and is the first number to start adding. If you do not use a second argument, the sum function will add to 0. Let’s try to use the sum() function with two integers:
x = 2 y = 6 print(sum(x, y))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) 1 print(sum(x,y)) TypeError: 'int' object is not iterable
The code is unsuccessful because the first argument is an integer and is not iterable.
Solution
You can put our integers inside an iterable object to solve this error. Let’s put the two integers in a list, a tuple, a set and a dictionary and then use the sum() function.
x = 2
y = 6
tuple_sum = (x, y)
list_sum = [x, y]
set_sum = {x, y}
dict_sum = {x: 0, y: 1}
print(sum(tuple_sum))
print(sum(list_sum))
print(sum(set_sum))
print(sum(dict_sum))
8 8 8 8
The code successfully runs. The result remains the same whether we use a tuple, list, set or dictionary. By default, the sum() function sums the key values.
Summary
Congratulations on reading to the end of this tutorial. The error “TypeError: ‘int’ object is not iterable” occurs when you try to iterate over an integer. If you define a for loop, you can use the range() function with the integer value you want to use as the stop argument. If you use a function that requires an iterable, such as the sum() function, you must put your integers inside an iterable object like a list or a tuple.
For further reading on the ‘not iterable’ TypeError go to the articles:
- How to Solve Python TypeError: ‘NoneType’ object is not iterable.
- How to Solve Python TypeError: ‘method’ object is not iterable.
Go to the online courses page on Python to learn more about Python for data science and machine learning.
Have fun and happy researching!
So, you have encountered the exception, i.e., TypeError: ‘int’ object is not iterable. In the following article, we will discuss type errors, how they occur and how to resolve them. You can also check out our other articles on TypeError here.
What is a TypeError?
The TypeError occurs when you try to operate on a value that does not support that operation. Let’s see an example of the TypeError we are getting.
number_of_emp = int(input("Enter the number of employees:"))
for employee in number_of_emp:
name = input("employee name:")
dept = input("employee department:")
sal = int(input("employee salary:"))

Before we understand why this error occurs, we need to have some basic understanding of terms like iterable, dunder method __iter__.
Iterable
Iterable are objects which generate an iterator. For instance, standard python iterable are list, tuple, string, and dictionaries.
All these data types are iterable. In other words, they can be iterated over using a for-loop. For instance, check this example.
from pprint import pprint
names = ['rohan','sunny','ramesh','suresh']
products = {
'soap':40,
'toothpaste':100,
'oil':60,
'shampoo':150,
'hair-gel':200
}
two_tuple = (2,4,6,8,9,10,12,14,16,18,20)
string = "This is a random string."
for name in names:
print(name,end=" ")
print("n")
for item,price in products.items():
pprint(f"Item:{item}, Price:{price}")
print("n")
for num in two_tuple:
print(num,end=" ")
print("n")
for word in string:
print(word,end=" ")

![[Fixed] Module Seaborn has no Attribute Histplot Error](https://www.pythonpool.com/wp-content/uploads/2023/01/Fixed-Module-Seaborn-has-no-Attribute-Histplot-Error-300x157.webp)
__iter__ dunder method
__iter__ dunder method is a part of every data type that is iterable. In other words, for any data type, iterable only if __iter__ method is contained by them. Let’s understand this is using some examples.
For iterable like list, dictionary, string, tuple:
You can check whether __iter__ dunder method is present or not using the dir method. In the output image below, you can notice the __iter__ method highlighted.

Similarly, if we try this on int datatype, you can observe that __iter__ dunder method is not a part of int datatype. This is the reason for the raised exception.

How to resolve this error?
Solution 1:
Instead of trying to iterate over an int type, use the range method for iterating, for instance.
number_of_emp = int(input("Enter the number of employees:"))
for employee in range(number_of_emp):
name = input("employee name:")
dept = input("employee department:")
sal = int(input("employee salary:"))

Solution 2:
You can also try using a list datatype instead of an integer data type. Try to understand your requirement and make the necessary changes.
random.choices ‘int’ object is not iterable
This error might occur if you are trying to iterate over the random module’s choice method. The choice method returns values one at a time. Let’s see an example.
import random num_list = [1,2,3,4,5,6,7,8,9] for i in random.choice(num_list): print(i)

Instead, you should try something like this, for instance, using a for loop for the length of the list.
import random num_list = [1,2,3,4,5,6,7,8,9] for i in range(len(num_list)): print(random.choice(num_list))

jinja2 typeerror ‘int’ object is not iterable
Like the above examples, if you try to iterate over an integer value in the jinja template, you will likely face an error. Let’s look at an example.
{% for i in 11 %}
<p>{{ i }}</p>
{% endfor %}
The above code tries to iterate over integer 11. As we explained earlier, integers aren’t iterable. So, to avoid this error, use an iterable or range function accordingly.
![[Fixed] JavaScript error: IPython is Not Defined](https://www.pythonpool.com/wp-content/uploads/2023/01/javascript-error-ipython-is-not-defined-300x157.webp)
FAQs on TypeError: ‘int’ object is not iterable
Can we make integers iterable?
Although integers aren’t iterable but using the range function, we can get a range of values till the number supplied. For instance:num = 10
print(list(range(num)))
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
How to solve self._args = tuple(args) TypeError ‘int’ object is not iterable problem?
This is a condition when the function accepts arguments as a parameter. For example, multiprocessing Process Process(target=main, args=p_number) here, the args accepts an iterable tuple. But if we pass an integer, it’ll throw an error.
How to solve TypeError’ int’ object is not iterable py2exe?
py2exe error was an old bug where many users failed to compile their python applications. This is almost non-existent today.
Conclusion
In this article, we tried to shed some light on the standard type error for beginners, i.e. ‘int’ object is not iterable. We also understood why it happens and what its solutions are.
Other Errors You Might Encounter
-
![[Fixed] Module Seaborn has no Attribute Histplot Error](https://www.pythonpool.com/wp-content/uploads/2023/01/Fixed-Module-Seaborn-has-no-Attribute-Histplot-Error-300x157.webp)
[Fixed] Module Seaborn has no Attribute Histplot Error
●January 18, 2023
-
![[Fixed] JavaScript error: IPython is Not Defined](https://www.pythonpool.com/wp-content/uploads/2023/01/javascript-error-ipython-is-not-defined-300x157.webp)
[Fixed] JavaScript error: IPython is Not Defined
by Rahul Kumar Yadav●January 18, 2023
-
![[Fixed] “io.unsupportedoperation not readable” Error](https://www.pythonpool.com/wp-content/uploads/2023/01/io.unsupportedoperation-not-readable--300x157.webp)
[Fixed] “io.unsupportedoperation not readable” Error
by Rahul Kumar Yadav●January 18, 2023
-
![[Fixed] “Index Object Has No Attribute tz_localize” Error](https://www.pythonpool.com/wp-content/uploads/2023/01/index-object-has-no-attribute-tz_localize-300x157.webp)
[Fixed] “Index Object Has No Attribute tz_localize” Error
by Rahul Kumar Yadav●January 18, 2023
It’s quite common for your code to throw a typeerror, especially if you’re just starting out with Python. The reason for this is that the interpreter expects variables of certain types in certain places in the code.
We’ll look at a specific example of such an error: "typeerror: 'int' object is not iterable".
Exercise: Run this minimal example and reproduce the error in your online Python shell!
Let’s start decomposing this error step-by-step!
Background Integer & Iterable
First, it’s worth understanding what int and iterable are.
The int type in Python, as in almost all programming languages, is a type for storing integers such as 1, 2, 3, -324, 0. There can be many variables of type int in our program. We can assign values to them ourselves directly:
a = 5
In this case, we will most often understand what is a type of our variable. But the value can, for example, be returned from a function. Python uses implicit typing. Implicit typing means that when declaring a variable, you do not need to specify its type; when explicitly, you must. Therefore, by assigning the result of a function to a variable, you may not be clearly aware of what type your variable will be.
s1 = sum([1, 2, 3]) print(s1) print(type(s1))
Output:
6 <class 'int'>
Here’s another example:
s2 = iter([1, 2, 3]) print(s2) print(type(s2))
Output:
<list_iterator object at 0x7fdcf416eac8> <class 'list_iterator'>
In this example, s1 is an integer and is of type int. This number is returned by the sum function with an argument in the form of a list of 3 elements. And the variable s2 is of type list_iterator, an object of this type is returned by the iter function, whose argument is the same list of 3 elements. We’ll talk about iteration now.
Iteration is a general term that describes the procedure for taking the elements of something in turn.
More generally, it is a sequence of instructions that is repeated a specified number of times or until a specified condition is met.
An iterable is an object that is capable of returning elements one at a time. It is also an object from which to get an iterator.
Examples of iterable objects:
- all sequences: list, string, tuple
- dictionaries
- files
It seems that the easiest way to find out what exactly our function is returning is to look at the documentation.
So we see for the iter: iter(object[, sentinel]) Return an iterator object.
But for the sum we have nothing about a type of returning value. Check it out by yourself!
So, the typeerror: ‘int’ object is not iterable error occurs when the interpreter expects an iterable object and receives just an integer. Let’s consider the most common examples of such cases.
Invalid ‘sum’ Argument
We already wrote about the sum function. It returns the int value. The sum function takes at most two arguments. The first argument must be an object that is iterable. If it’s a collection of some sort, then it’s probably a safe assumption that it’s iterable. The second argument to the sum function is optional. It’s a number that represents the first number you’ll start adding to. If you omit the second argument, then you’ll start adding to 0. For novice Python programmers, it seems common sense that a function should return the sum of its arguments. Often they try to apply it like this:
a = 4 b = 3 sum(a, b)
Output:
TypeError Traceback (most recent call last)
<ipython-input-12-35b280174f65> in <module>()
1 a = 4
2 b = 3
----> 3 sum(a, b)
TypeError: 'int' object is not iterable
But we see that this leads to an error. We can fix this situation by pre-writing our variables for summation in an iterable object, in a list or a tuple, or a set, for example:
a = 4
b = 3
tuple_sum = (a, b)
list_sum = [a, b]
set_sum = {a, b}
dict_sum = {a: 0, b: 1}
print(sum(tuple_sum))
print(sum(list_sum))
print(sum(set_sum))
print(sum(dict_sum))
Output:
7 7 7 7
As you can see, the result remains the same. Whether we are using pre-entry into a tuple, list, set, or even a dictionary. Note that for dictionaries, the sum function sums key values by default.
You can even write one variable to a list and calculate the sum of this list. As a search on stackoverflow shows, newbies in programming often try to calculate the sum of one element, which of course leads to an error.
a = 2 sum(a)
Output:
TypeError Traceback (most recent call last)
<ipython-input-21-5db7366faaa2> in <module>()
1 a = 2
----> 2 sum(a)
TypeError: 'int' object is not iterable
But if we pass an iterable object for example a list (even if it consists of one element) to the function then the calculation is successful.
a = 2 list_sum = [a] print(sum(list_sum))
Output:
2
Another way to form such a list is to use the list.append method:
a = 2
list_sum = []
list_sum.append(a)
print('Sum of "a":', sum(list_sum))
b = 5
list_sum.append(b)
print('Sum of "a" and "b":',sum(list_sum))
Output:
''' Sum of "a": 2 Sum of "a" and "b": 7 '''
Let’s consider a more complex version of the same error. We have a function that should calculate the sum of the elements of the list including the elements of the nested lists.
def nested_sum(list_):
total = 0
for item in list_:
item = sum(item)
total = total + item
return total
list1 = [1, 2, 3, [4, 5]]
print(nested_sum(list1))
Output:
TypeError Traceback (most recent call last)
<ipython-input-35-c30be059e3a4> in <module>()
6 return total
7 list1 = [1, 2, 3, [4, 5]]
----> 8 nested_sum(list1)
<ipython-input-35-c30be059e3a4> in nested_sum(list_)
2 total = 0
3 for item in list_:
----> 4 item = sum(item)
5 total = total + item
6 return total
TypeError: 'int' object is not iterable
You can probably already see what the problem is here. The loop parses the list into its elements and goes through them. The items in our list are numbers 1, 2, 3 and a list [4, 5]. You can compute a sum of the list but you can’t get the sum of one number in Python. So we have to rewrite code.
def nested_sum(list_):
total = 0
for item in list_:
if type(item) == list:
item = sum(item)
total = total + item
return total
list1 = [1, 2, 3, [4, 5]]
print(nested_sum(list1))
Output:
15
Now, in the loop, we first of all check the type of our local variable 'item' and if it is a list, then with a clear conscience we calculate its sum and rewrite the variable 'item' with the resulting value. If it’s just a single element, then we add its value to the 'total'.
Incorrect use of ‘for’ loop
Let’s consider another common case of this error. Can you see right away where the problem is?
n = 10 for i in n: print(i)
Output:
TypeError Traceback (most recent call last)
<ipython-input-24-7bedb9f8cc4c> in <module>()
1 n = 10
----> 2 for i in n:
3 print(i)
TypeError: 'int' object is not iterable
Perhaps the error in this construction is associated with the tradition of teaching children the Pascal language at school. There you can actually write something similar: for i:=1 to n do.
But in Python ‘for’ loops are used for sequential traversal. Their construction assumes the presence of an iterable object. In other languages, a ‘for each’ construct is usually used for such a traversal.
Thus, the ‘for’ construct in Python expects an iterable object which to be traversed, and cannot interpret an integer. This error can be easily corrected using the function ‘range’. Let’s see how our example would look in this case.
n = 10 for i in range(n): print(i)
Output:
0 1 2 3 4 5 6 7 8 9
The ‘range’ function can take 3 arguments like this: range(start, stop[, step]). The ‘start’ is the first number from which the loop will begin, ‘stop’ is the number at which the loop will end. Please note that the number ‘stop’ will not be included in the cycle. The ‘step’ is how much the number will differ at each next iteration from the previous one. By default, ‘start’ has a value of 0, ‘step’=1, and the stop parameter must be passed compulsory. More details with examples can be found in the documentation. https://docs.python.org/3.3/library/stdtypes.html?highlight=range#range
for i in range(4, 18, 3): print(i)
Output:
4 7 10 13 16
Here is a small example of using all three parameters of the ‘range’ function. In the loop, the variable ‘i’ in the first step will be equal to 4, ‘i’ will never be greater than or equal to 18, and will increase in increments of 3.
Problems With Tuples
The next example where an error "typeerror: ‘int’ object is not iterable" can occur is multiple assignment of values using a tuple. Let’s take a look at an example.
a, b = 0
Output:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-6-6ffc3a683bb5> in <module>() ----> 1 a, b = 0 TypeError: 'int' object is not iterable
It’s a very pythonic way of assignment but you should be careful with it. On the left we see a tuple of two elements ‘a’ and ‘b’, so to the right of the equal sign there must also be a tuple (or any other iterable object) of two elements. Don’t be intimidated by writing a tuple without parentheses, this is an allowable way in Python.
So to fix this error, we can write the assignment like this:
a, b = 0, 0 print(a) print(b)
Output:
0 0
And a few more examples of how you can assign values to several variables at once:
a, b = (1, 2)
c, d = {3, 4}
e, f = [5, 6]
print(a, b, c ,d ,e, f)
Output:
1 2 3 4 5 6
A similar problem can arise if you use a function that returns multiple values as a tuple. Consider, for example, a function that returns the sum, product, and result of division of two numbers.
def sum_product_division(a, b):
if b != 0:
return a + b, a * b, a / b
else:
return -1
sum_, product, division = sum_product_division(6, 2)
print("The sum of numbers is:", sum_)
print("The product of numbers is:", product)
print("The division of numbers is:", division)
Output:
The sum of numbers is: 8 The product of numbers is: 12 The division of numbers is: 3.0
Note that I have added an underscore to the variable name ‘sum_’. This is because the word ‘sum’ is the name of the built-in function that we discussed above. As you can see, in the case when ‘b’ is not equal to zero, our code works correctly, the variables take the appropriate values. Now let’s try to pass the value ‘b’ equal to 0 to the function. Division by zero will not occur, since we provided for this in the function and return -1 as an error code.
sum_, product, division = sum_product_division(6, 0)
print("The sum of numbers is:", sum_)
print("The product of numbers is:", product)
print("The division of numbers is:", division)
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-6c197be50200> in <module>()
----> 1 sum_, product, division = sum_product_division(6, 0)
2 print("The sum of numbers is:", sum_)
3 print("The product of numbers is:", product)
4 print("The division of numbers is:", division)
TypeError: 'int' object is not iterable
The error “TypeError: 'int' object is not iterable” occurs again. What’s the matter? As I already said, this situation is similar to the previous one. Here we also try to assign values to several variables using a tuple. But our function when there is a danger of division by zero returns not a tuple but the only value of the error code ‘-1’.
How to fix it? For example, we can check the type of a returning value. And depending on this type, already output the result. Let’s do it!
result = sum_product_division(6, 0)
if type(result) == int:
print("Error, b should not be zero!")
else:
sum_, product, division = result
print("The sum of numbers is:", sum_)
print("The product of numbers is:", product)
print("The division of numbers is:", division)
Output:
Error, b should not be zero!
Here’s another example:
result = sum_product_division(6, 3)
if type(result) == int:
print("Error, b should not be zero!")
else:
sum_, product, division = result
print("The sum of numbers is:", sum_)
print("The product of numbers is:", product)
print("The division of numbers is:", division)
Output:
The sum of numbers is: 9 The product of numbers is: 18 The division of numbers is: 2.0
We can also redesign our function to return the result of the operation from the beginning of the tuple. And use some trick when assigning variables. Take a look at this:
def sum_product_division(a, b):
if b != 0:
return "Ok", a + b, a * b, a / b
else:
return ("Error",)
status, *results = sum_product_division(6, 0)
print(status, results)
status, *results = sum_product_division(6, 2)
print(status, results)
Output:
Error [] Ok [8, 12, 3.0]
If division by zero is possible we return a tuple with a single element – the string ‘Error’. If everything is correct then we return a tuple where the first element is a status message – the string ‘Ok’ and then the results of the calculations follow sequentially: sum, product, result of division.
There can be many options here, because this is a function that we wrote ourselves, so we can fix it as we please. But it so happens that we use functions from libraries. For example here is an error from a topic on stackoverflow.
import subprocess data = subprocess.call(["echo", '''Hello World! Hello!''']) sum_lines = 0 for line in data: print(line) sum_lines += 1 print(sum_lines)
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-8d4cf2cb9ee0> in <module>()
3 Hello!'''])
4 sum_lines = 0
----> 5 for line in data:
6 print(line)
7 sum_lines += 1
TypeError: 'int' object is not iterable
I rewrote the code a bit so that the essence is clear. We want to run a command on the command line and count the number of lines printed on the screen. In our case, it will be just a command to display a little message to the World.
We should read a documentation to figure it out. The subprocess module allows you to spawn new processes, connect to their input /output /error pipes, and obtain their return codes. We see that the ‘call’ function starts the process on the command line, then waits for its execution and returns the execution result code! That’s it! The function returned the code of execution. It’s integer and we are trying to traverse this integer in a loop. Which is impossible, as I described above.
What to do? Explore the documentation for the module further. And so we find what we need. The ‘check_output’ function. It returns everything that should be displayed in the console when the command being passed is executed. See how it works:
import subprocess
data=subprocess.check_output(["echo", '''Hello World!
Hello!'''])
sum_lines = 0
for line in data.splitlines():
print(line)
sum_lines +=1
print(sum_lines)
Output:
b'Hello World!' b'Hello!' 2
Great! We got a byte string separated by newline symbols ‘n’ at the output. And we can traverse over it as shown with a ‘splitlines’ function. It returns a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless ‘keepends’ parameter is given and true.
Thus, we fixed the error and got what we needed, but had to do a little research in the documentation. This study of documentation is one of the most effective ways to improve your programming skills.
The snag with lists
Often the error "TypeError: 'int' object is not iterable" appears when using various functions related to lists. For example I have a list of my exam grades. I want to add to it a grade in physical education which I passed perfectly in contrast to math. I am trying to do it like this:
grades = [74, 85, 61] physical_education_mark = 100 grades += physical_education_mark
I’m using the most conventional method to perform the list concatenation, the use of “+” operator. It can easily add the whole of one list behind the other list and hence perform the concatenation. But it doesn’t work here. Because list concatenation is only possible for two lists. We cannot combine list and number. The most obvious way to solve this problem is to use the ‘append’ function. It is designed just to do that. It adds an item to the list. The argument can also be an integer.
grades = [74, 85, 61] physical_education_mark = 100 grades.append(physical_education_mark) print(grades)
Output:
[74, 85, 61, 100]
Voila! We did it! Of course, if we really want to use the ‘+’ operator, we can pre-write our physical education grade in a list with one element, for example like this:
grades = [74, 85, 61] physical_education_mark = 100 grades += [physical_education_mark] print(grades)
Output:
[74, 85, 61, 100]
The result is expectedly the same as the previous one. Move on.
Another list-related problem is when you’re trying to add element with ‘extend‘ method. This method can be very useful to concatenate lists. Unlike the ‘+’ operator, it changes the list from which it is called. For example, I need to add new semester grades to the grades list. It’s easy to do with the method ‘extend’:
grades = [74, 85, 61] new_semestr_grades = [85, 79] physical_education_mark = 100 grades.extend(new_semestr_grades) print(grades)
Output:
[74, 85, 61, 85, 79]
So we did it easily but wait! We forgot our perfect physical education score!
grades = [74, 85, 61] new_semestr_grades = [85, 79] physical_education_mark = 100 grades.extend(new_semestr_grades) grades.extend(physical_education_mark) print(grades)
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-48-6d49503fc731> in <module>()
3 physical_education_mark = 100
4 grades.extend(new_semestr_grades)
----> 5 grades.extend(physical_education_mark)
6 print(grades)
TypeError: 'int' object is not iterable
And we can’t do it like this. ‘extend’ is waiting for iterable object as an argument. We can use ‘append’ method or pre-writing manner.
grades = [74, 85, 61] new_semestr_grades = [85, 79] physical_education_mark = [100] grades.extend(new_semestr_grades) grades.extend(physical_education_mark) print(grades)
Output:
[74, 85, 61, 85, 79, 100]
Did you notice the difference? I originally defined the variable ‘physical_education_mark’ as a list with one item. And this works perfect!
Now suppose we need a function that will find the location of variables in the formula “A + C = D – 6”. If you know that each variable in the formula is denoted by one capital letter. We’re trying to write it:
def return_variable_indexes(formula):
for element in formula:
if element.isupper():
indexes = list(formula.index(element))
return indexes
print(return_variable_indexes("A + C = D - 6"))
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-44-5a9b17ff47ae> in <module>()
5 return indexes
6
----> 7 print(return_variable_indexes("A + C = D - 6"))
<ipython-input-44-5a9b17ff47ae> in return_variable_indexes(formula)
2 for element in formula:
3 if element.isupper():
----> 4 indexes = list(formula.index(element))
5 return indexes
6
TypeError: 'int' object is not iterable
Yes, we got the same error again. Let’s try to understand what’s the matter. We go through the elements of the string ‘formula’. And if this element is a upper-case letter then we use the ‘index’ function to find its position in the string. And try to write it into a list ‘indexes’. So we have two functions ‘index’ and ‘list’. What is returning value of the ‘index’ function? It is an integer number the position at the first occurrence of the specified value. So we’re trying to add this to the list ‘indexes’ with a ‘list’ function. And stop here! The ‘list’ constructor takes one argument. It should be an iterable object so that could be a sequence (string, tuples) or collection (set, dictionary) or any iterator object. Not an integer number of course. So we can use ‘append’ method again and get the result we need:
def return_variable_indexes(formula):
indexes = []
for element in formula:
if element.isupper():
indexes.append(formula.index(element))
return indexes
print(return_variable_indexes("A + C = D - 6"))
Output:
[0, 4, 8]
And just for fun you can do it as a one-liner using a list comprehension and the ‘enumerate’ method. It takes iterable object as an argument and returns its elements with index as tuples (index, element) one tuple by another:
def return_variable_indexes(formula):
return [index_ for index_, element in enumerate(formula) if element.isupper()]
print(return_variable_indexes("A + C = D - 6"))
Output:
[0, 4, 8]
Conclusion
We have considered some cases in which an error “TypeError: ‘int’ object is not iterable” occurs. This is always a situation where the interpreter expects an iterable object, and we provide it an integer.
The most common cases of such errors:
- incorrect sum argument;
- incorrect handling of tuples;
- related to various functions and methods of lists
I hope that after reading this article you will never have a similar problem. And if it suddenly arises then you can easily solve it. You may need to read the documentation for this though =)
Typeerror int object is not iterable occurs when try to iterate int type object in the place of an iterable object like tuple, list, etc. In this article, Firstly we will understand what is Iterable object in python. Secondly we will understand the root cause for this error. At last we will see this error from multiple real time scenario and then see how to fix the same.
What is Iterable object in Python ?
A python object is iterable when its element is in some sequence. We can use next() function to traverse in the iterable object. Some example for Iterable object in python is list, typle, set, dict etc.
Let’s see a real scenario where we get this above error. Then see will discuss the root cause.
my_list=[1,2,3,4,5,6]
for i in len(my_list):
print(i)
When we run the above code, we get the below error.

As we can see in the above example, We have used len(my_list) which is nothing but int type object. That’s the reason we get this error int object is not iterable. Anyways in the next section, We will see how to fix this.
Typeerror int object is not iterable (Fix)-
Well, We have two different ways to fix this.
1.Using list as an iterable object-
we can use list (my_list) directly in the place of using len(my_list). Just because the list is an iterable object.

2.Using range() function-
Secondly, We can use range() function over len(my_list). Here is the way can we achieve it.
my_list=[1,2,3,4,5,6]
for i in range(len(my_list)):
print(my_list[i])

One more important thing is that we are using the range function. Which is just an iterable object. Hence in the print statement, we use list subscription.
Conclusion-
See, There may be very real scenarios where we get the error int object is not iterable. But Underline root cause will be the same as we have mentioned in the above section. Hence We can use the above solution in those situations.
Int object is not iterable is one the most common error for python developers. I hope now you must solve the above error. Please let me know if you have doubts about this topic. Please comment below in the comment box.
Thanks
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
We respect your privacy and take protecting it seriously
Thank you for signup. A Confirmation Email has been sent to your Email Address.
Something went wrong.