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?
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?
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
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).