The Python "TypeError: 'type' object is not iterable" occurs when we try to iterate over a class that is not iterable, e.g. forget to call the range() function. To solve the error, make the class iterable by implementing the __iter__() method.
The Python "TypeError: argument of type 'int' is not iterable" occurs when we use the membership test operators (in and not in) with an integer value. To solve the error, correct the assignment or convert the int to a string, e.g. str(my_int) .
The "TypeError: 'X' is not iterable" occurs when using the for...of loop with a right hand-side value that is not iterable, e.g. an object. To solve the error, use the Object. keys() or Object. values() methods to get an array with which you can use the for...of loop.
In the example below, we see how a list a is iterated through using a for ... in loop and each element can be accessed via variable x . Similar to list , range is a python type that allows us to iterate on integer values starting with the value start and going till end while stepping over step values at each time.
Your problem is with this line:
number4 = list(cow[n])
It tries to take cow[n]
, which returns an integer, and make it a list. This doesn't work, as demonstrated below:
>>> a = 1
>>> list(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>
Perhaps you meant to put cow[n]
inside a list:
number4 = [cow[n]]
See a demonstration below:
>>> a = 1
>>> [a]
[1]
>>>
Also, I wanted to address two things:
:
at the end.input
like that, since it evaluates its input as real Python code. It would be better here to use raw_input
and then convert the input to an integer with int
.To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum
:
>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>
This is very simple you are trying to convert an integer to a list object !!! of course it will fail and it should ...
To demonstrate/prove this to you by using the example you provided ...just use type function for each case as below and the results will speak for itself !
>>> type(cow)
<class 'range'>
>>>
>>> type(cow[0])
<class 'int'>
>>>
>>> type(0)
<class 'int'>
>>>
>>> >>> list(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>
If the case is:
n=int(input())
Instead of -> for i in n:
-> gives error- int
object is not iterable
Use -> for i in range(0,n):
works fine..!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With