Does anyone know how to access the index itself for a list like this:
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?
|
Using additional state variable, such as 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 builtin function enumerate, available in both Python 2 and 3:
Check out PEP 279 for more. |
|||||||||||||
|
Its pretty simple to start it from
Edit1Important hint, though a little misleading, since |
||||
|
|
|||||||||||||||||
|
Primary answer What you are asking for is the Pythonic equivalent of this, which is the algorithm most programmers of lower-level languages would use:
Python's
This code sample is fairly well the canonical example of the difference between code that is idiomatic of Python and code that is not. Idiomatic code is sophisticated (but not complicated) Python, written in the way that it was intended to be used. Idiomatic code is expected by the designers of the language, which means that usually this code is not just more readable, but also more efficient. Getting a count Even if you don't need indexes as you go, but you need a count of the iterations, sometimes desirable, you can start with
Step by step explanation To break these examples down, say we have a list of items that we want to iterate over with an index:
Now we pass this iterable to enumerate, creating an enumerate object:
We can pull the first item out of this iterable that we would get in a loop with the
And we see we get a tuple of
we can use what is referred to as "sequence unpacking" to extract the elements from this two-tuple:
and when we inspect
|
||||
|
Old fashioned way:
List comprehension:
|
||||
|
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
|
|||||
|
First of all, the indexes will be from 0 to 4. Programming languages start counting from 0; don't forget that or you will come across an index out of bounds exception. All you need in the for loop is a variable counting from 0 to 4 like so:
Keep in mind that I wrote 0 to 5 because the loop stops one number before the max. :) To get the value of an index use
|
||||
|
I don't know if the following is pythonic or not, but it uses the Python function
|
||||
|
You can do it with this code:
Use this code if you need to reset the index value at the end of the loop:
|
||||
|
This way you can extend a list. Extend means you can add multiple values at a time. To append this list you have to write the code given below:
This way you can add a single value at a time. If you write |
||||
|
The better way to get the index of each element of the sequence:
|
|||||
|