[Python-Dev] Adding start to enumerate()

Guido van Rossum guido at python.org
Tue May 13 16:25:01 CEST 2008


On Tue, May 13, 2008 at 2:40 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> Terry Reedy wrote:
>>
>> "Nick Coghlan" <ncoghlan at gmail.com> wrote in message
>> news:4828C59B.8070008 at gmail.com...
>> | I'd like to hear from Raymond before we do this. I'm pretty sure we had
>> | a reason for *not* doing it that way in when enumerate() was added, but
>> | I can't remember what that reason might have been...
>>
>> http://bugs.python.org/issue2831
>
> Thanks. I think this part is the main reason I see a start argument to
> enumerate as potentially problematic:
>
> """all variants can easily be misread as starting at the nth item in the
>   sequence (much like islice() does now):   enumerate(3, 'abcdefg') -->
>   (3,'d') (4,'e') (5, 'f') (6, 'g')."""

So the ambiguity is that enumerate(it, start=N) could be taken as
skipping the first N items of it rather than adding N to the index it
returns. (And it is my own argument!) I'd like to withdraw this
argument. There are two separate use cases for using enumerate(): one
is to iterate over a sequence and to have a handy index by which to
update the value in the sequence. Another is for 1-based counting,
usually when printing 1-based ordinals (such as line numbers in files,
dates in a month or months in a year, etc.). N-based counting is less
common but still conceivable. However I see no use for skipping items
from the start, and if that use case ever came up, passing a slice to
enumerate() would be the appropriate thing to do. In fact, if you
passed in a slice, you might also want to pass a corresponding start
value so the indices produced match those of the original sequence.

So, I am still in favor of adding a new argument to enumerate().

I'm neutral on the need for a keyword (don't think it would hurt, not
sure how much it matters). I'm strongly against making it an optional
*leading* argument like Raymond proposed; that's a style I just don't
want to promote, range() and the curses module notwithstanding.

> Is the need to use zip(count(3), seq) for the offset index case really such
> a burden given the associated benefits in keeping the builtin function
> really simple and easy to understand?

Yes, zip(count(3), seq) is too complex for this simple use case. I've
always solved this so far with this less-than-elegant but certainly
simpler idiom (except for users stuck in the tradition of for-loops in
certain older languages :-):

for i, line in enumerat(lines):
  i += 1
  print "%4d. %s" % (i, line)

and variants thereof.

[Also added to the issue.]

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list