on the popularity of loops while and for

Hope Rouselle hrouselle at jevedi.com
Thu Sep 2 09:23:29 EDT 2021


Terry Reedy <tjreedy at udel.edu> writes:

> On 8/28/2021 9:31 AM, Hope Rouselle wrote:
>> I'd like get a statistic of how often each loop is used in practice.
>
> My guess is that for loops are at least twice as common as while loops.

Scanning just the Python 3.9.6's Lib/ directory --- using the ast module
and the program someone kindly posted here ---, I found for loop
appearing 598% more times than while loops.  The ratio was something
like that 6.98..., excluding files that due to encoding errors (or
whatever) could not be parsed.  (I reported these numbers elsewhere in
this thread.)

>> I was trying to take a look at the Python's standard libraries --- those
>> included in a standard installation of Python 3.9.6, say --- to see
>> which loops are more often used among while and for loops.  Of course,
>> since English use the preposition ``for'' a lot, that makes my life
>> harder.  Removing comments is easy, but removing strings is harder.  So
>> I don't know yet what I'll do.
>
> Try something like
>
> fors = 0
> for file in files:
>     for line in file:
>         if re.match(r"/s*for .* in ", line):
>             fors += 1
>
> This excludes comprehensions, which have replaced some for loops.

That's nice too.  Thanks for the alternative.


More information about the Python-list mailing list