NoobEditor NoobEditor - 1 year ago 72
Python Question

'int' object is not iterable when trying to assign loop index

This is really strange, please take a loop at code snippet below, when i remove

num=i
, all works fine but with it, it is causing iteration issue.

Error code

In [17]: prim_list=[]
...: for i in range(2,101):
...: print i
...: num=i,count=0 # line with issue
...: for j in range(1,i/2):
...: div=j
...: if(num%div==0):
...: count=count+1
...: if(count==1):
...: prim_list.append(num)
...:
2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-17-a8dd2a52322e> in <module>()
2 for i in range(2,101):
3 print i
----> 4 num=i,count=0
5 for j in range(1,i/2):
6 div=j

TypeError: 'int' object is not iterable


Working fine

In [19]: prim_list=[]
...: for i in range(2,101):
...: count=0 # notice num=i assignment is removed
...: for j in range(1,i/2):
...: div=j
...: if(num%div==0):
...: count=count+1
...: if(count==1):
...: prim_list.append(num)
...: print "done"
...:
done


What i am not understanding is why the assignment is causing the loop iteration error!!??

any help is appreciated!

Answer Source

You are using a chained assignment:

num=i,count=0

is

num = (i, count) = 0

Where num = 0 and (i, count) = 0 are assigned. Because 0 is not an iterable of length 2, it can't be assigned to a tuple of targets.

Use

num, count = i, 0

or

num = i
count = 0

instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download