In your question, you write "how do I access the loop index, from 1 to 5 in this case?"
However, the index for a list runs from zero. So, then we need to know if what you actually want is the index and item for each item in a list, or whether you really want numbers starting from 1. Fortunately, in Python, it is easy to do either or both.
First, to clarify, the enumerate
function iteratively returns the index and corresponding item for each item in a list.
alist = [1, 2, 3, 4, 5]
for n, a in enumerate(alist):
print("%d %d" % (n, a))
The output for the above is then,
0 1
1 2
2 3
3 4
4 5
Notice that the index runs from 0. This kind of indexing is common among modern programming languages including Python and C.
If you want your loop to span a part of the list, you can use the standard Python syntax for a part of the list. For example, to loop from the second item in a list up to but not including the last item, you could use
for n, a in enumerate(alist[1:-1]):
print("%d %d" % (n, a))
Note that once again, the output index runs from 0,
0 2
1 3
2 4
That brings us to the start=n
switch for enumerate()
. This simply offsets the index, you can equivalently simply add a number to the index inside the loop.
for n, a in enumerate(alist, start=1):
print("%d %d" % (n, a))
for which the output is
1 1
2 2
3 3
4 4
5 5