enumerate improvement proposal

Raymond Hettinger python at rcn.com
Tue Oct 31 11:16:09 EST 2006


James Stroud wrote:
> I think that it would be handy for enumerate to behave as such:
>
> def enumerate(itrbl, start=0, step=1):
>    i = start
>    for it in itrbl:
>      yield (i, it)
>      i += step

I proposed something like this long ago and Guido has already rejected
it.  Part of the reason is that it doesn't match his mental model of
enumerate being about pairing sequence elements with their indices.
Another reason is that the syntax has more than one obvious
interpretation:

     enumerate('abcdef', 2) -->  (2, 'c'), (3, 'd'), ...
     enumerate('abcdef', 2) -->  (0, 'c'), (1, 'd'), ...
     enumerate('abcdef', 2) -->  (2, 'a'), (2, 'b'), ...

Also, the order of arguments is odd in comparison with the output order
-- this suggests a syntax like enumerate(2, 'abcdef') --> (2, 'a'), (3,
'b') ...

FWIW, it is not hard to roll-your-own with something like:

    for pagenum, page in izip(count(1), book): ...

The izip/count combination runs at C speed, matches enumerate() in its
efficiency, and is arguably clearer in expressing its intended
behavior.


Raymond




More information about the Python-list mailing list