for loop without variable

Basilisk96 basilisk96 at gmail.com
Fri Jan 11 01:56:18 EST 2008


On Jan 10, 10:36 pm, Marty <mart... at earthlink.net> wrote:
> Hrvoje Niksic wrote:
> > Mike Meyer <mwm-keyword-python.b4b... 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?

But it does:

data_in = (1,2,3,4,5)
data_out = []

data_out += [[] for blah in data_in]

print data_out
[[], [], [], [], []]


Cheers,
-Basilisk96



More information about the Python-list mailing list