Int object is not iterable python ошибка

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 runni

Int Object is Not Iterable – Python Error [Solved]

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

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!

The following code is giving me error Python

TypeError: 'int' object is not iterable:

Code:

hosts = 2
AppendMat = []
Mat = np.zeros((hosts,hosts))
Mat[1][0] = 5
for i in hosts:
    for j in hosts:
        if Mat[i][j]>0 and Timer[i][j]>=5:
            AppendMat.append(i)

How could I fix the error —

TypeError: 'int' object is not iterable?

Secondly how can I append both the values of i and j if the if condition is true? Here I’m trying to append i only.

RAM's user avatar

RAM

2,3861 gold badge21 silver badges33 bronze badges

asked Sep 3, 2013 at 15:09

user1921843's user avatar

1

Try this:

for i in xrange(hosts):

answered Sep 3, 2013 at 15:10

jimifiki's user avatar

jimifikijimifiki

5,3142 gold badges34 silver badges57 bronze badges

1

You need to iterate over a range based on hosts, not hosts itself:

for i in range(hosts):      # Numbers 0 through hosts-1
    for j in range(hosts):  # Numbers 0 through hosts-1

You can append both numbers as a tuple:

 AppendMat.append((i,j))

or simply append them individually

AppendMat.extend([i,j])

depending on your needs.

answered Sep 3, 2013 at 15:11

chepner's user avatar

chepnerchepner

478k70 gold badges502 silver badges652 bronze badges

You cannot iterate over integer (hosts):

>>> for i in 2:
...     print(i)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

You should use range(n) to iterate n times:

>>> for i in range(2):
...     print(i)
...
0
1

answered Sep 3, 2013 at 15:11

falsetru's user avatar

falsetrufalsetru

350k62 gold badges704 silver badges625 bronze badges

probably you meant range(2) instead of hosts

answered Sep 3, 2013 at 15:11

Srinivas Reddy Thatiparthy's user avatar

hosts is an int, so for i in hosts will not work, as the error explains. Perhaps you meant

for i in range(hosts):

The same goes for the second for-loop.

(See range(); in Python 2.x use xrange())


By the way this whole thing can be a single list comprehension:

AppendMat = [i for i in range(hosts) 
                   for j in range(hosts) 
                       if Mat[i][j]>0 and Timer[i][j]>=5]

answered Sep 3, 2013 at 15:11

arshajii's user avatar

arshajiiarshajii

126k24 gold badges234 silver badges283 bronze badges

0

the for statement apply to the Python concept «iterable», like list, tuple, etc.. An int is not an iterable.

so you should use range() or xrange(), which receive an int and produce an iterable.

second, do you mean append a tuple: append((i,j)) or a list: append([i,j]) ? I’m not quite clear about the question.

answered Sep 3, 2013 at 15:21

Bor's user avatar

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.

TypeError: 'int' object is not iterable  

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.

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.

typeerror int object is not iterable example

typeerror int object is not iterable example

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.

int object is not iterable Fix-1

int object is not iterable Fix-1

 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])

int object is not iterable Fix-2

int object is not iterable Fix-2

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.

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))

Typeerror: ‘Int’ Object Is Not Iterable

Python TypeError: ‘int’ object is not iterable 3
Python Typeerror Int Object Is Not Iterable
Python TypeError: ‘int’ object is not iterable 4

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: "))

Avatar Of Srinivas Ramakrishna

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.

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:"))

TypeError: 'int' object is not iterable

TypeError: ‘int’ object is not iterable

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=" ")

Outputs of different iterables

Outputs of different iterables

“Other Commands Don’t Work After on_message” in Discord Bots

__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.

__iter__ method present in list data type

__iter__ method present in list data type

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.

__iter__ method not a part of int datatype

__iter__ method not a part of int datatype

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:"))

TyperError resolved using the range method

TypeError resolved using the range method.

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)

random.choices ‘int’ object is not iterable

random.choices ‘int’ object is not iterable

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))

Iterating over random.choice

Iterating over random.choice

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.

[Resolved] NameError: Name _mysql is Not Defined

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

  • “Other Commands Don’t Work After on_message” in Discord Bots

    “Other Commands Don’t Work After on_message” in Discord Bots

    February 5, 2023

  • Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    by Rahul Kumar YadavFebruary 5, 2023

  • [Resolved] NameError: Name _mysql is Not Defined

    [Resolved] NameError: Name _mysql is Not Defined

    by Rahul Kumar YadavFebruary 5, 2023

  • Troubleshooting “Cannot import name ‘escape’ from ‘jinja2′” Error

    Troubleshooting “Cannot import name ‘escape’ from ‘jinja2′” Error

    by Rahul Kumar YadavFebruary 5, 2023

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.

Get offers and scholarships from top coding schools illustration

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

Email

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!

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 =)

In simple words, any object that could be looped over is iterable. For instance, a list object is iterable and so is an str object. The list numbers and string names are iterables because we are able to loop over them (using a for-loop in this case).  In this article, we are going to see how to check if an object is iterable in Python.

Examples: 

Input: “Hello”

Output: object is not iterable

Explanation: Object could be like( h, e, l, l, o)

Input: 5

Output: int’ object is not iterable

Example 1:

Python3

name = "Hello"

for letter in name:

  print(letter, end = " ")

Output:

H e l l o

Example 2:

Python3

number = 5

for i in number:

  print(i)

Output

TypeError: 'int' object is not iterable

However, an int object is not iterable and so is a float object. The integer object number is not iterable, as we are not able to loop over it.

Checking an object’s iterability in Python

We are going to explore the different ways of checking whether an object is iterable or not. We use the hasattr() function to test whether the string object name has __iter__ attribute for checking iterability. However, this check is not comprehensive.

Method 1: Using __iter__ method check.

Python3

name = 'Roster'

if hasattr(name, '__iter__'):

  print(f'{name} is iterable')

else:

  print(f'{name} is not iterable')

Output:

Roster is iterable

Method 2: Using the Iterable class of collections.abc module.

We could verify that an object is iterable by checking whether it is an instance of the Iterable class. The instance check reports the string object as iterable correctly using the Iterable class. This works for Python 3 as well. For Python 3.3 and above, you will have to import the Iterable class from collections.abc and not from collections like so:

Python3

from collections.abc import Iterable

name = 'Roster'

if isinstance(name, Iterable):

  print(f"{name} is iterable")

else:

  print(f"{name} is not iterable")

Output:

Roster is iterable

Method 3: Using the iter() builtin function.

The iter built-in function works in the following way:

  • Checks whether the object implements __iter__, and calls that to obtain an iterator.
  • If that fails, Python raises TypeError, usually saying “C object is not iterable,” where C is the class of the target object.

Code:

Python3

name = "Roster"

try:

  iter(name)

  print("{} is iterable".format(name))

except TypeError:

  print("{} is not iterable".format(name))

Output:

Roster is iterable

Type checking

Here we will check the type of object is iterable or not.

Python3

from collections.abc import Iterable  

if isinstance(4, Iterable):

    print("iterable")

else:

    print("not iterable")

Output:

not iterable

Понравилась статья? Поделить с друзьями:
  • Int object is not callable питон как исправить
  • Intel raid 1 volume как исправить
  • Int error python
  • Intel r visual fortran run time error
  • Int cannot be dereferenced java ошибка