getting an index in a for loop

Paul Rubin phr-n2003b at NOSPAMnightsong.com
Sat Feb 1 04:59:55 CET 2003


Erik Max Francis <max at alcyone.com> writes:
> >     >>> for index, char in enumerate('abcdefg'):
> >     ...     print index, char
> 
> Both of these are nice and tight idiomatically, but they actually have
> to build the lists of tuples, and so can be prohibitive if you expect
> the sequence (whether it's a string or not) to be very long indeed.

Do they really???  I would have hoped that enumerate would build an
iterator, something like

  def enumerate(seq):
     i = 0
     for s in seq:
        yield s
        i += 1
 
If enumerate really does build the whole list, either I'm missing
something basic or else there was a big blunder.




More information about the Python-list mailing list