python for loop

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Apr 2 05:59:55 EDT 2009


En Wed, 01 Apr 2009 08:04:12 -0300, andrew cooke <andrew at acooke.org>  
escribió:

> something i don't think has been mentioned much - if you're using
> "range()" in your python code then you're almost always doing it wrong.
>
> i just grepped lepl and i use range 20 times in 9600 lines of code.  out
> of those, all but 3 are in "quick and dirty" tests or experimental code,
> not in the main library itself (which is 6300 lines).
>
> (1) where i need to access two adjacent members of a list, and which has  
> a
> comment in the code explaining why it is not an error (in other words, i
> was so unhappy with my code i needed to leave a note explaining why it  
> was
> like that)

 From your description I guess this "range" usage could have been avoided,  
using enumerate instead. A silly example:

for i,elem in enumerate(some_list):
   if i>0:
     prev = some_list[i-1]
     print (elem+prev)/2

instead of:

for i in range(1, len(some_list)):
   elem = some_list[i]
   prev = some_list[i-1]
   print ...

> (2) a use irrelevant to this discussion because i do not use the value to
> an index an array.
>
> (3) in the rather complex implementation of a circular buffer.

I can't tell, but perhaps enumerate() could have been used here too?

> so in a small/moderate size library of 6000 lines (including blanks and
> comments, but excluding tests and exploratory code) the only time i have
> used range with array indices i was either unhappy with the code, or
> implementing a complex data structure.

Maybe the ratio is even less than that.

-- 
Gabriel Genellina




More information about the Python-list mailing list