enumerate improvement proposal

Peter Otten __peter__ at web.de
Sun Oct 29 08:50:40 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
> 
> This allows much more flexibility than in the current enumerate,
> tightens up code in many cases, and seems that it would break no
> existing code. Yes, I have needed this behavior with enumerate, like
> tonight and the current example. I put the "step" parameter in for
> conceptual symmetry with slicing.
> 
> Here is a case use (or is it use case?):

I don' think you have a use case here:

# untested
def find_interval(value, bounds, funny_offset=0, reverse=False):
    bounds = sorted(bounds)
    if reverse:
        index = len(bounds) - bisect.bisect_left(bounds, value)
    else:
        index = bisect.bisect_right(bounds, value)
    return index + funny_offset

You can tell by its name which of the arguments I would have omitted :-)

> Of course, I haven't used step here. 

That seems to be typical. The only use case I've ever come across is start=1
for output aimed at a human reader.

> Even in this trivial example the 
> proposed enumerate cleans the code and logic, eliminating a couple of
> plus signs. For this real-world example, the practical requirement for
> reversing the bins obfuscates somewhat the de-obfuscation provided by
> the proposed enumerate. But I think that it might be obvious that the
> proposed enumerate could help significantly in cases a bit more
> complicated than this one.

Of course you get these claimed advantages from a self-written function,
too.

> Any thoughts?

You have my support for adding a start parameter to enumerate(). I fear it
won't make a difference.

Peter



More information about the Python-list mailing list