Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)
edited by

How do I access the index itself for a list like the following?

ints = [8, 23, 45, 12, 78]

for i in ints:

print('item #{} = {}'.format(???, i))

I want to get this output:

item #1 = 8 

item #2 = 23 

item #3 = 45 

item #4 = 12 

item #5 = 78

When I loop through it using a for loop, how do I access the loop index, from 1 to 5 in this case?

1 Answer

0 votes
by (106k points)

If you want to access the index in 'for' loop then you can use the built-in Python function enumerate(), this function is available in both Python 2 and 3 below is the piece of code that uses enumerate() function:-

ints = [8, 23, 45, 12, 78]

for idx, val in enumerate(ints):

print(idx, val)

image

Related questions

+2 votes
3 answers
asked May 21, 2019 in Python by Aditya98 (1.3k points)
0 votes
1 answer
asked Jun 26, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 2, 2019 in Python by Anurag (33.1k points)

Browse Categories

...