2

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

0

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

0

you should write

for cl in mylist:

len() is not iterable.

2 Comments

But it returns TypeError: list indices must be integers, not str
@Ria: cl is not the index. It's the item itself. Please use a print statement to see what value cl has.
0
for cl in mylist:
    print repr(cl)
    #do whatever

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.