tags:

views:

6202

answers:

3

Anyone knows how to access the index itself so for a list like this:

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

when I loop through it using a for loop, how do I make access the for loop index, from 1 to 5 in this case?

A: 
for i in range(len(ints)):
   print i, ints[i]
David Hanak
That should probably be `xrange` for pre-3.0.
Ben Blank
No, unless the speed is needed one shouldn't optimize.
Georg
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
A: 

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)
>>>
Charlie Martin
+60  A: 

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:

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

Check out PEP 279 for more.

Mike Hordecki
+1 because that's exactly what this function is for.
Brian