While programming in Python, it is a common practice to use loops such as for loops and while loops. These are used for iterating over lists and dictionaries for performing a variety of operations on the elements. But programmers often encounter an error called TypeError: ‘int’ object is not iterable.
This type of error occurs when the code is trying to iterate over a list of integer elements.
Let us understand it more with the help of an example.
Example 1
# Initializing an integer variable
Var = 5
# Iterating through a loop
# Using an integer value
for i in Var:
print("This will raise an error")
Output
File "none3.py", line 6, in <module>
for i in var:
TypeError: 'int' object is not iterable
Explanation
In the above example, we are trying to iterate through a for loop using an integer value. But the integers are not iterable. As the Var variable holds a single integer value 5, it cannot be iterated using a for loop or any other loop.
This is because of the absence of __iter__ method. Which we have discussed about below in example 2.
Thus the error “TypeError: int object is not iterable” occurs.
Example 2
# Initializing the list
MyList = [2,4,8,3]
# Iterating through a List
for x in MyLlist:
print(x)
Output
2
4
8
3
Explanation
In the above example, we printing the elements of the list using the for loop. since the list is an iterable object, thus we can use the for loop to iterate through it. Thus, the TypeError is not encountered here. Dictionaries are also iterable in Python using the loops.
To know whether an object is iterable or not we can use the dir() method to check for the magic method __iter__ . If this magic method is present in the properties of specified objects then that item is said to be iterable
To check, do: dir(list) or dir(5)
Code
List= [ ]
print(dir(list))
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']
__iter__ magic method is present.
Code
# Initializing an integer variable
Var = 5
# Printing methods associated with integer
print(dir(Var))
Output
['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']
On reviewing the output of the code. We notice that __iter__ magic method is absent. Thus, integers are not iterable.
Conclusion
The presence of the magic method __iter__ is what makes an object iterable. From the above article, we can conclude that. The __iter__ method is absent in the float object. Whereas it is present in the list object. Thus integer is not iterable object, unlike list.
If you have read our previous article, the ‘NoneType’ object is not iterable. You already know why Python throws ‘typeerror‘, and it occurs basically during the iterations like for and while loops.
The most common scenario where developers get this error is when you try to iterate a number using for loop where you tend to forget to use the range()
method, which creates a sequence of a number to iterate.
Consider the following code snippet to accept grades for each student in a class.
students=int(input('Please enter the number of students in the class: '))
for number in students:
math_grade=(input("Enter student's Maths grade: "))
science_grade=(input("Enter student's Science grade: "))
social_grade=(input("Enter student's Scoial grade: "))
# Output
Please enter the number of students in the class: 5
Traceback (most recent call last):
File "c:ProjectsTryoutslistindexerror.py", line 3, in <module>
for number in students:
TypeError: 'int' object is not iterable
The above code is pretty straightforward, which reads input on the total number of students in a class, and for each student, it accepts the subject grades.
The easier way everyone thinks here is to go with for loop and iterate the number of students to accept the grade. If you run the code, Python will throw a TypeError: ‘int’ object is not iterable.
Why does Python throw TypeError: ‘int’ object is not iterable?
In Python, unlike lists, integers are not directly iterable as they hold a single integer value and do not contain the ‘__iter__
‘ method; that’s why you get a TypeError.
You can run the below command to check whether an object is iterable or not.
print(dir(int))
print(dir(list))
print(dir(dict))
If you look at the output screenshots, int does not have the ‘__iter__’ method, whereas the list and dict have the '
__iter__'
method.
How to fix TypeError: ‘int’ object is not iterable?
There are two ways you can resolve the issue, and the first approach is instead of using int, try using list if it makes sense, and it can be iterated using for and while loop easily.
Second approach if you still want to iterate int object, then try using the range()
method in the for loop, which will eventually generate a list of sequential numbers.
students=int(input('Please enter the number of students in the class: '))
for number in range(students):
math_grade=(input("Enter student's Maths grade: "))
science_grade=(input("Enter student's Science grade: "))
social_grade=(input("Enter student's Scoial grade: "))
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
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 =)
Encountering an error is not a problem; it’s a learning opportunity. While developing in Python, you may have seen an error “‘int’ object is not iterable”.
What does this mean? How do I solve it? Those are the questions we’re going to answer in this article. We will discuss what the “‘int’ object is not iterable” error is, why it is raised, and how you can solve it.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
The Problem: typeerror: ‘int’ object is not iterable
“typeerror: ‘int’ object is not iterable”
There are two parts to this error message: TypeError and the error message.
A TypeError is raised when a function is applied to an object of the wrong data type. For instance, if you try to apply a mathematical function to a string, or call a value like a function which is not a function, a TypeError is raised.
The error message tells us that you have tried to iterate over an object that is not iterable. Iterable objects are items whose values you can access using a “for loop”.
A Practice Scenario
One of the most common scenarios in which this error is raised is when you try to use a for loop with a number. This mistake is made because it’s easy to forget to use the range() function when you are using a for loop.
Consider the following code snippet:
def count_occurrence(values, to_find): number_of_occurrences = 0 for v in len(values): if values[v] == to_find: number_of_occurrences += 1 return number_of_occurrences values = [1, 2, 3, 3] check_for_threes = count_occurrence(values, 3) print(check_for_threes)
This code snippet uses one function. The count_occurance function counts how many times a number appears in the “values” list. This function iterates over all the values in “values” and keeps a running total of all those equal to a particular number. This number is specified as a parameter called “to_find”.
In our main program, we define a list called “values” with four values. We call our count_occurrence function to count how many threes are in our list of values. We then print out the response to the console.
Let’s run our code:
Traceback (most recent call last): File "main.py", line 9, in <module> check_for_threes = count_occurrence(values, 3) File "main.py", line 3, in count_occurrence for v in len(values): TypeError: 'int' object is not iterable
Oh no! An error has been raised. Now that we’ve replicated this error, we can solve it.
The Solution
Our error tells us that we’ve tried to iterate over an object that is not iterable. If we look at the error message in detail, we can see it points us to the line where the problem occurs:
The problem with this line is that we are trying to iterate over a number.
len(values) is equal to 4. That’s how many values are in the list “values”. If we try to iterate over a number, nothing happens. This is because for loops only work with iterable objects.
To solve this problem, we need to make sure our for loop iterates over an iterable object. We can add a range()
statement to our code to do this:
for v in range(len(values)):
This statement will create an iterable object with a list of values in the range of 0 and the number of items in the “values” list.
Let’s try to run our code again with the range()
statement. Our code returns:
Our code has successfully found all the instances of 3 in the list. Our code has counted them all up and then printed the total number of times 3 appears in the list to the console.
Conclusion
TypeErrors are a common type of error in Python. They occur when you try to apply a function on a value of the wrong type. An “‘int’ object is not iterable” error is raised when you try to iterate over an integer value.
To solve this error, make sure that you are iterating over an iterable rather than a number.
Now you’re ready to solve this error like a Pythonista!