a good explanation

Diez B. Roggisch deets at nospam.web.de
Thu May 25 08:39:53 EDT 2006


s99999999s2003 at yahoo.com schrieb:
> hi
> my friend has written a loop like this
> cnt = 0
> files = [a,b,c,d]
> while cnt < len(files) :
>    do_something(files[cnt])
> 
> i told him using
> for fi in files:
>    do_something(fi)
> 
> is better, because the while loop method makes another call to
> len..which is slower..
> am i partly right? or is there a better explanation for using the for
> method.?

Several good reasons:

   - his loop won't terminate, as he (or you trying to copy his efforts) 
forgot to increment cnt

   - he needs additional statements & state. The more you have of this, 
the likelier you make errors. he could for example write <= len(files)

   - the whole loop is noisier to the eye, makes it harder to grasp what 
it's all about

It seems that your friend comes from a language like C or JAVA (pre 1.5) 
where the for loop was basically what his while loop above is: one 
initializer, one condition test, one last statement, mostly incrementing 
the counter.

Python's for is build around the concept of an iterable. Which lists, 
tuples, strings and many other things are - and thus  the last, and 
possibly strongest reason is: its not idiomatic Python, he tries top 
shoehorn python into some schemes he's used from other languages. Don't 
do that, accept Python & it's ways for a better life :)


Diez




More information about the Python-list mailing list