Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - index in enumerate

Tags:

python

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
    ...
like image 682
Eagle Avatar asked Jan 17 '26 14:01

Eagle


2 Answers

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, ...

like image 60
Ashoka Lella Avatar answered Jan 20 '26 06:01

Ashoka Lella


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

like image 35
senshin Avatar answered Jan 20 '26 04:01

senshin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!