Iterate a list with indexes in Python
Solution 1:
>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
... print i, val
...
0 3
1 4
2 5
3 6
>>>
Solution 2:
Yep, that would be the enumerate
function! Or more to the point, you need to do:
list(enumerate([3,7,19]))
[(0, 3), (1, 7), (2, 19)]
Solution 3:
Here's another using the zip
function.
>>> a = [3, 7, 19]
>>> zip(range(len(a)), a)
[(0, 3), (1, 7), (2, 19)]
Solution 4:
Here it is a solution using map function:
>>> a = [3, 7, 19]
>>> map(lambda x: (x, a[x]), range(len(a)))
[(0, 3), (1, 7), (2, 19)]
And a solution using list comprehensions:
>>> a = [3,7,19]
>>> [(x, a[x]) for x in range(len(a))]
[(0, 3), (1, 7), (2, 19)]