for loop without variable

Mike Meyer mwm-keyword-python.b4bdba at mired.org
Thu Jan 10 22:59:07 EST 2008


On Thu, 10 Jan 2008 22:36:56 -0500 Marty <martyb1 at earthlink.net> wrote:
> I recently faced a similar issue doing something like this:
> 
>      data_out = []
>      for i in range(len(data_in)):
>      	data_out.append([])

More succinctly:

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

Or, as has already been pointed out:

data_out = [[] for _ in data_in]

> 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 I'm curious - what's the difference between the "foreach" you have
in mind and the standard python "for"?

   <mike
-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.



More information about the Python-list mailing list