What does enumerate mean ?
Here is the solution is
Here is the code is
>>> elements = ('foo', 'bar', 'baz') >>> for elem in elements: ... print elem ... foo bar baz >>> for count, elem in enumerate(elements): ... print count, elem ... 0 foo 1 bar 2 baz
The enumerate() starts counting at 0 but a second integer argument, it’ll start from that number instead.
>>> for count, elem in enumerate(elements, 42): ... print count, elem ... 42 foo 43 bar 44 baz
The to re-implement enumerate() in Python, there are two ways of achieving that;
one using itertools.count() to do the counting, the other manually counting in a generator function
from itertools import count def enumerate(it, start=0): # return an iterator that adds a counter to each element of it return zip(count(start), it) def enumerate(it, start=0): count = start for elem in it: yield (count, elem) count += 1
The actual implementation in C is closer to the latter, with optimisations to reuse a single tuple object for the common fori….,
for item in enumerate(["a", "b", "c"]): print item
(0, "a") (1, "b") (2, "c")