+2 votes
2 views
in Python by (1.3k points)
edited by

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?

3 Answers

0 votes
by (46.1k points)

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)

There are some other methods too but this is the easiest and fastest one.

Hope this will help you.

0 votes
by (107k points)

It is very simple you can start it from 1 other than 0:

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.

0 votes
by (20.3k points)

It's very simple to start it from 1 other than 0:

for index, item in enumerate(iterable, start=1):

   print index, item

Related questions

0 votes
1 answer
asked Jul 22, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
asked Jun 26, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
asked Jul 2, 2019 in Python by Anurag (33.2k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...