Iteration count in python

Posted on Sun 01 December 2013 in Notes

This is a quite nifty "trick" in Python. Often times you want to iterate an object (array or list, or something else) and you want to use each item you iterate over while keeping count of how many iterations you've been through. The enumerate() function does this!

In [14]: datapoints = np.random.randint(10, size = (4,4))

In [15]: targets = np.random.randint(10, size = (4,4))

In [16]: for i, data in enumerate(datapoints):
   ....:     print i, '\t', data, data == targets[i]
   ....:     
0     [9 8 4 1]    [False False False False]
1     [2 1 9 1]    [False False False False]
2     [1 9 8 1]    [False False False False]
3     [5 5 0 4]    [False False False False]