Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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?

share|improve this question
134  
Incidently, Python lists are indexed starting from 0. –  bobince Feb 6 '09 at 22:55

11 Answers 11

up vote 1793 down vote accepted
+500

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:

for idx, val in enumerate(ints):
    print idx, val

Check out PEP 279 for more.

share|improve this answer
16  
PHP has foreach ($ints as $idx => $val) print $idx, $val; –  cweiske Jun 15 '11 at 15:47
8  
@cweiske: It is not the same, $idx may not be zero-based number of the loop, so it is different and less reliable than iterating through $ints and using index variable. Although in case of array(8,23,45,12,78) and other non-associative arrays this will work, you have to be sure $ints is not associative. I am not sure about the instances of the classes implementing Iterator interface. –  Tadeck Mar 1 '12 at 2:03
66  
If we edit the code to for idx, val in enumerate(ints, start=1):, the indices will go from 1 to 5 as it was asked. –  Till Dec 20 '12 at 15:43

Its pretty simple to start it from 1 other than 0.

for index in enumerate(iterable, start=1):
   print index

Edit1

Important hint, though a little misleading, since index will be a tuple (idx, item) here. Good to go.

share|improve this answer
for i in range(len(ints)):
   print i, ints[i]
share|improve this answer
7  
That should probably be xrange for pre-3.0. –  Ben Blank Feb 6 '09 at 22:52
1  
No, unless the speed is needed one shouldn't optimize. –  Georg Schölly Feb 6 '09 at 23:07
23  
One shouldn't prematurely optimize, though I agree in this case, due to having the same code work in 2.x and 3.x. –  Roger Pate Feb 7 '09 at 9:38
    
Use enumerate instead –  saulspatz Aug 1 at 21:28

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:

index = 0 # python indexing starts at zero
for item in items:
    print(index, item)
    index += 1

Python's enumerate function reduces the visual clutter by removing the accounting for the indexes, and encapsulating the iterable into another iterable (an enumerate object) that yields a two-item tuple of the index, and the item that the original iterable would provide. That looks like this:

for index, item in enumerate(items, start=0):   # default is zero
    print(index, item)

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 1 and the final number will be your count.

for count, item in enumerate(items, start=1):   # default is zero
    print(item)

print('there were {0} items printed'.format(count))

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:

items = ['a', 'b', 'c', 'd', 'e']

Now we pass this iterable to enumerate, creating an enumerate object:

enumerate_object = enumerate(items) # the enumerate object

We can pull the first item out of this iterable that we would get in a loop with the next function:

iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)

And we see we get a tuple of 0, the first index, and 'a', the first item:

(0, 'a')

we can use what is referred to as "sequence unpacking" to extract the elements from this two-tuple:

index, item = iteration
#   0,  'a' = (0, 'a') # essentially this.

and when we inspect index, we find it refers to the first index, 0, and item refers to the first item, 'a'.

>>> print(index)
0
>>> print(item)
a
share|improve this answer

Old fashioned way:

for ix in range(len(ints)):
    print ints[ix]

List comprehension:

[ (ix, ints[ix]) for ix in range(len(ints))]

>>> ints
[1, 2, 3, 4, 5]
>>> for ix in range(len(ints)): print ints[ix]
... 
1
2
3
4
5
>>> [ (ix, ints[ix]) for ix in range(len(ints))]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> lc = [ (ix, ints[ix]) for ix in range(len(ints))]
>>> for tup in lc:
...     print tup
... 
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
>>>
share|improve this answer

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:

for i in range(len(sequence)):
    # work with index i

Looping over both elements and indices can be achieved either by the old idiom or by using the new 'zip' built-in function[2]:

for i in range(len(sequence)):
    e = sequence[i]
    # work with index i and element e

or

for i, e in zip(range(len(sequence)), sequence):
    # work with index i and element e

via http://www.python.org/dev/peps/pep-0212/

share|improve this answer
15  
This won't work for iterating through generators. Just use enumerate(). –  Tadeck Mar 31 '13 at 18:24

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:

for x in range(0, 5):

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

list[index]
share|improve this answer

I don't know if the following is pythonic or not, but it uses the Python function enumerate and prints the enumerator and the value.

int_list = [8, 23, 45, 12, 78]
for index in enumerate(int_list):
   print index
(0, 8)
(1, 23)
(2, 45)
(3, 12)
(4, 78)
share|improve this answer

You can do it with this code:

ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value

Use this code if you need to reset the index value at the end of the loop:

ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value
    if index >= len(ints)-1:
        index = 0
share|improve this answer

ints = [9, 23, 45, 12, 78] ints.extend([1,2,3,4,5,6,7,8]) for idx, val in enumerate(ints): print(idx,val)

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:

ints = [9, 23, 45, 12, 78] ints.append([1]) for idx, val in enumerate(ints): print(idx,val)

This way you can add a single value at a time. If you write ints.append([1]) so this will create a sub list for this element.

share|improve this answer

The better way to get the index of each element of the sequence:

for indx , value in enumerate(arraySquence):
    print (indx , value )
share|improve this answer
1  
Why give the same answer that has already been given long ago? –  Richard de Wit Jan 8 at 11:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.