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?
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?
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)
>>>
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.