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.
Typeerror int object is not iterable – (Root cause)
Let’s see a real scenario where we get this above error. Then see will discuss the root cause.
for i in len(my_list):
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.
for i in range(len(my_list)):
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.
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.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.