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?

kartikeykant18
  • 1,737
  • 6
  • 28
  • 42
  • What are you trying to accomplish? – placeybordeaux Dec 07 '13 at 05:41
  • its just a code i saw i meant to say what would the code mean??? – kartikeykant18 Dec 07 '13 at 05: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) – CodenameLambda Apr 25 '16 at 17:09

2 Answers2

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
Community
  • 1
  • 1
bcorso
  • 45,608
  • 10
  • 63
  • 75
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).

alpacahaircut
  • 337
  • 1
  • 3
  • 11