Iteration over Lists and Strings

Alex Martelli aleaxit at yahoo.com
Sat Aug 28 03:02:12 EDT 2004


Michel Claveau - abstraction méta-galactique non triviale en fuite
perpétuelle. <unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom> wrote:

> and enumerate is more fast than index.

Oh, absolutely.  sequence.index(anitem) takes time proportional to
len(sequence), for the average item.  If you repeat that operation for
all items in sequence, you end up with total time proportional to the
SQUARE of len(sequence) -- a LOT, for long sequences,  enumerate itself
takes constant time, and looping over all items that enumerate yields
takes time proportional to the number of items (costant time per item).

If you're familiar with big-O notation, we're talking O(N) vs O(N
square)... not the kind of performance issue one can ignore, for long
sequences, because the difference in performance keeps going up and up
without bounds as the sequence grows longer.


Alex



More information about the Python-list mailing list