Back
How can someone access the index itself for a list like the following :
intg = [8, 23, 45, 12, 78, 90]
When for is used to loop through, How can I access the loop index, from 1 to 6 in this case?
An additional state variable such as an index variable is considered non-pythonic which we normally use in languages like C or PHP.
We can use the built in function available in both Python 2 and 3 enumerate() it’s a better option
foridx, valin enumerate(intg):print(idx, val)
foridx, valin enumerate(intg):
print(idx, val)
There are some other methods too but this is the easiest and fastest one.
Hope this will help you.
It is very simple you can start it from 1 other than 0:
for index, item in enumerate(iterable, start=1): print index, item
for index, item in enumerate(iterable, start=1):
print index, item
You can use the following video tutorials to clear all your doubts:-
Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.
It's very simple to start it from 1 other than 0:
30.9k questions
32.9k answers
500 comments
665 users