I am just starting to learn Python. At what index value in python does a for loop start from?
For example, if I have a text file with 390 lines, and I iterate:
for i, word in enumerate(f)
Does the value of the index start from 0 or from 1?
Also, if I want to print out every 30th line in the file, then will I have to iterate like this?
if i+1 in [30,60,90,120,150,180,210,240,270,300,330,360,390]:
print i
...
when you are using for loop with a list. It includes all the elements in the list starting from the zero'th:
if f=['x','y','z']
for i, word in enumerate(f):
print i, word
would output:
0 x
1 y
2 z
for printing every 30th line. You can use
for i in range(0,390,30):
which would output: 0, 30 ,60 90, ...
For your first question: the index starts at 0, as is generally the case in Python. (Of course, this would have been very easy to try for yourself and see).
>>> x = ['a', 'b', 'c']
>>> for i, word in enumerate(x):
print i, word
0 a
1 b
2 c
For your second question: a much better way to handle printing every 30th line is to use the mod operator %:
if i+1 % 30 == 0:
print i
# ...
This is slightly better than testing for membership in range since you don't have to worry about edge effects (i.e. since range gives a half-open interval that is open on the right end).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With