enumerate improvement proposal

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Oct 30 00:08:09 CET 2006

James Stroud <jstroud at mbi.ucla.edu> writes:

> Fredrik Lundh wrote:
> > why is it this function's job to add an offset to the actual
> > sequence index?
> The code is for an economist. She is insistent on starting with the
> first bin as 1.

Note that 'enumerate' is actually a built-in type, and 'enumerate()'
is the constructor returning a new object of that type.

A special case isn't special enough to change the built-in type.

    >>> print enumerate("ABCDE")
    <enumerate object at 0xa7d642ac>
    >>> print list(enumerate("ABCDE"))
    [(0, 'A'), (1, 'B'), (2, 'C'), (3, 'D'), (4, 'E')]

    >> def obstinate_economist_enumerate(items):
    ...     seq = [(i+1, x) for (i, x) in enumerate(items)]
    ...     return iter(seq)
    >>> print obstinate_economist_enumerate("ABCDE")
    <listiterator object at 0xa7d6408c>
    >>> print list(obstinate_economist_enumerate("ABCDE"))
    [(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E')]

This doesn't produce an 'enumerate' object; if you really want that,
you could subclass 'enumerate', but it seems the above function does
what you want.

 \        "I installed a skylight in my apartment. The people who live |
  `\                          above me are furious!"  -- Steven Wright |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list