python iterate list with index - Accessing the index in 'for' loops?

for loop python / python / loops / list

How do I access the index 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

Aaron Hall



Answer #1
items = [8, 23, 45, 12, 78]

for i in enumerate(items):
    print("index/value", i)
# index/value (0, 8)
# index/value (1, 23)
# index/value (2, 45)
# index/value (3, 12)
# index/value (4, 78)
items = [8, 23, 45, 12, 78]

for i, val in enumerate(items):
    print("index", i, "for value", val)
# index 0 for value 8
# index 1 for value 23
# index 2 for value 45
# index 3 for value 12
# index 4 for value 78
items = [8, 23, 45, 12, 78]

for i, val in enumerate(items):
    print("index", i)
# index 0
# index 1
# index 2
# index 3
# index 4