Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Accessing the index in 'for' loops?

how would I get to the list in a for loop 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 by it applying a for loop, how do I access the loop index, from 1 to 5 in this case?
by

2 Answers

nemo011
You can try the enumerate function to get the index. Here's an example

ints = [8, 23, 45, 12, 78]
for i, number in enumerate(ints, start=1):
print('item #{} = {}'.format(i, number))
MounikaDasa
Use enumerate to get the index with the element as you iterate:

for index, item in enumerate(items):
print(index, item)

And note that Python's indexes start at zero, so you would get 0 to 4 with the above. If you want the count, 1 to 5, do this:

for count, item in enumerate(items, start=1):
print(count, item)

Login / Signup to Answer the Question.