enumerate improvement proposal

S

Steven D'Aprano

Divorce is obviously the only answer. How could you end up marrying
someone who counts from one and not zero? ;-)


"Should array indices start at 0 or 1? My compromise of 0.5 was rejected
without, I thought, proper consideration." (Stan Kelly-Bootle)
 
R

Raymond Hettinger

James said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,224
Latest member
BettieToom

Latest Threads

Top