Looping over lists

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun May 6 03:06:22 EDT 2007


En Sat, 05 May 2007 05:15:32 -0300, kaens <apatheticagnostic at gmail.com>  
escribió:

> I think the for i in range() is more readable (Maybe because I'm
> coming from a c-style syntax language background) -  but what would
> the benefits of using enumerate be (other that being more . . .
> pythonesque?)

If you want to iterate over a sequence and process each item, you could do  
this (as one would do in C):

for i in range(len(values)):
   dosomethingwith(values[i])

Problems: values[i] gets translated into values.__getitem__(i), and that  
requires a lookup for the __getitem__ method and a function call; and you  
don't actually need the index i, but it's created anyway.
In this case the best (and fastest) way in Python is:

for item in values:
   dosomethingwith(item)

No spurious variable, no method lookup, no aditional function call. But  
what if you need *also* the index? On earlier Python versions one had to  
go back to the first method; enumerate() was made just for this case:

for i, item in enumerate(values):
   dosomethingwith(item, i)

You get all the advantages of the iterator approach plus the index  
available.

-- 
Gabriel Genellina



More information about the Python-list mailing list