for loop without variable

Marty martyb1 at earthlink.net
Thu Jan 10 22:36:56 EST 2008


Hrvoje Niksic wrote:
> Mike Meyer <mwm-keyword-python.b4bdba at mired.org> writes:
> 
>> It sounds to me like your counter variable actually has meaning,
> 
> It depends how the code is written.  In the example such as:
> 
> for meaningless_variable in xrange(number_of_attempts):
>     ...
> 
> the loop variable really has no meaning.  Rewriting this code only to
> appease pylint is exactly that, it has nothing with making the code
> more readable.
> 
>> you've hidden that meaning by giving it the meaningless name "i". If
>> you give it a meaningful name, then there's an obvious way to do it
>> (which you listed yourself):
>>
>>     while retries_left:
> [...]
> 
> This loop contains more code and hence more opportunities for
> introducing bugs.  For example, if you use "continue" anywhere in the
> loop, you will do one retry too much.

I recently faced a similar issue doing something like this:

     data_out = []
     for i in range(len(data_in)):
     	data_out.append([])

This caused me to wonder why Python does not have a "foreach" statement (and 
also why has it not come up in this thread)?  I realize the topic has probably 
been beaten to death in earlier thread(s), but does anyone have the short answer?



More information about the Python-list mailing list