How do I access the index itself for a list like the following?
ints = [8, 23, 45, 12, 78]
When I loop through it using a for
loop, how do I access the loop index, from 1 to 5 in this case?
How do I access the index itself for a list like the following?
ints = [8, 23, 45, 12, 78]
When I loop through it using a for
loop, how do I access the loop index, from 1 to 5 in this case?
In you 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 known 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.
The output for the above is then,
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
Note that once again, the output index runs from 0,
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 which the output is
As is the norm in Python there are several ways to do this. In all examples assume:
lst = [1, 2, 3, 4, 5]
1. Using enumerate (considered most idiomatic)
This is also the safest option in my opinion because the chance of going into infinite recursion has been eliminated. Both the item and its index are held in variables and there is no need to write any further code to access the item.
2. Creating a variable to hold the index (using
for
)3. Creating a variable to hold the index (using
while
)4. There is always another way
As explained before, there are other ways to do this that have not been explained here and they may even apply more in other situations. e.g using
itertools.chain
with for. It handles nested loops better than the other examples.To print tuple of (index, value) in list comprehension using a
for
loop:Output:
You can also try this:
The output is
Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic.
The better option is to use the built-in function
enumerate()
, available in both Python 2 and 3:Check out PEP 279 for more.
According to this discussion: http://bytes.com/topic/python/answers/464012-objects-list-index
Loop counter iteration
The current idiom for looping over the indices makes use of the built-in 'range' function:
Looping over both elements and indices can be achieved either by the old idiom or by using the new 'zip' built-in function[2]:
or
via http://www.python.org/dev/peps/pep-0212/