Ria
Ria

Reputation: 167

for loop in python

I just started with python.. I got an error with for loop.. What is the problem ??

  Traceback (most recent call last):
  File "userentry.py", line 34, in <module>
    userentry(p,i)
  File "userentry.py", line 26, in userentry
    for cl in len(mylist):
  TypeError: 'int' object is not iterable

Please help me

Upvotes: 2

Views: 2253

Answers (3)

jon_darkstar
jon_darkstar

Reputation: 16768

for cl in mylist:
    print repr(cl)
    #do whatever

Upvotes: 0

rmflow
rmflow

Reputation: 4765

you should write

for cl in mylist:

len() is not iterable.

Upvotes: 0

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56390

You can just iterate over the list, you don't iterate over the length of the list.

for cl in mylist:
    # do stuff

If you need to keep track of the index of the current item, use enumerate:

for idx, item in enumerate(mylist):
    # idx = index of current item
    # item = current item

When you try to do for cl in len(mylist), that's like saying for cl in 5 (if mylist has length of 5), which doesn't really make sense. If you want to just iterate over the indices of a list, it's best to use the enumerate example above, but you can also do

for i in range(len(mylist)):
    # mylist[i] is the ith item in the list

Though there are very few reasons to do this instead of just using the enumerate version above.

Upvotes: 8

Related Questions