0

I saw a code like this:

for i in val[0]:                  
    int(i)
    count += 1

where val is any defined list. What the for loop iterate over here. Let's suppose val[0] is 5, then will loop go on for 5 times?

3
  • What are you trying to accomplish? Commented Dec 7, 2013 at 5:41
  • its just a code i saw i meant to say what would the code mean??? Commented Dec 7, 2013 at 5:44
  • Just a little comment on the thing with loop through it 5 times: You can archive that by doing for i in range(5), because range returns a list (it doesn't anymore in Python3, because xrange became range) up to the argument. (Although different things happen if you put more than one argument into the function) Commented Apr 25, 2016 at 17:09

2 Answers 2

4

if val[0] is 5 you will get an error:

>>> for i in 5:
TypeError: 'int' object is not iterable

That code is only valid if val[0] is iterable

>>> # here val[0] = [1,2,3], which is an iterable list.
>>> val = [[1, 2, 3], [4, 5], [6], 7]
>>> for i in val[0]:
>>>     print i
1
2
3

This has a good explanation about what is iterable. Essentially, you can check for iterability by checking for the __iter__ method:

>>> hasattr([1,2,3,4], '__iter__')
True
>>> hasattr(5, '__iter__')
False

Strings can also be used in a for loop to iterate over characters, but for some reason they use __getitem__ instead of __iter__:

>>> hasattr([u"hello", '__iter__')
False
>>> hasattr([u"hello", '__getitem__')
True
Sign up to request clarification or add additional context in comments.

Comments

0

In python (and anything else I can think of)

for i in 5:
    int(i)
    count +=1

will throw an error, specifically in Python 2.7 you get

TypeError: 'int' object is not iterable

are the entries of val iterables themselves? So that for example val[0]=[0,1,2,3,4]. In this case the above code will work (assuming that you have initialized the variable count somewhere).

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.