Thoughts on PEP284

Alex Martelli aleax at aleax.it
Sat Sep 27 12:17:08 EDT 2003


David Eppstein wrote:
   ...
>> Really?  I would expect a common usage to be:
>> 
>>         for 0 <= index < len(list):
>>              do something with list[index]
> 
> Isn't that what the new enumerate(list) is for?

Not necessarily.  enumerate is for when you need the values of both index
AND somelist[index], which is clearly a pretty common case.  But sometimes
you don't care about the "previous value" of somelist[index].  E.g., say
that your specs are:

if issospecial(index) returns true, then, whatever the previous value
of somelist[index] might have been, it must be replaced with beeble.next().

Then, expressing this as:

    for index in range(len(somelist)):
        if issospecial(index):
            somelist[index] = beeble.next()

looks rather better to me than:

    for index, item in enumerate(somelist):
        if issospecial(index):
            somelist[index] = beeble.next()

where the fact that 'item' is being so deliberately REQUESTED... and
then utterly IGNORED... makes me wonder if the code's author may not
have committed some typo, or something.


Admittedly, these cases where you don't CARE about the previous values
of items ARE rare enough that enumerate use-cases vastly outnumber them.


Alex





More information about the Python-list mailing list