for loop without variable

Matimus mccredie at gmail.com
Thu Jan 10 23:58:51 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?

Pythons `for' essentially is foreach. The code below does the same
thing as what you have posted does. Actually, I've found that if you
find yourself ever doing range(len(data_in)) in python, it is time to
take a second look.

data_out = []
for x in data_in:
    data_out.append([])

`range' is just a function that returns a list.

Matt




More information about the Python-list mailing list