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, ...
Answer from Ashoka Lella on Stack OverflowIs there any reason to use enumerate to get index of items and print them?
using the 'enumerate' function to iterate over a list with index and value
A desperate plea for help (StackOverflow did not help)
why you expect StackOverflow to help when there is not clear clarity in your problem? I mean you didn't even mentioned the sequence conditions, why do you expect SO to help on this?
More on reddit.com[deleted by user]
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).
You can iter list with for: for i in range(len(list)): print(f"{i} {list[i]}")
And enumerate: for i, v in enumerate(list): print(f"{i} {v}")
Are there any difference?
Suppose you want to iterate over a list and access both the index and value of each element.
You can use this code:
# Original list
lst = ['apple', 'banana', 'cherry', 'grape']
# Iterate over the list with index and value
for i, fruit in enumerate(lst):
print(f"Index: {i}, Value: {fruit}")
# Output
# Index: 0, Value: apple
# Index: 1, Value: banana
# Index: 2, Value: cherry
# Index: 3, Value: grapeThe enumerate function returns a tuple containing the index and value of each element, which can be unpacked into separate variables using the for loop.