for loop without variable
Marty
martyb1 at earthlink.net
Fri Jan 11 01:48:43 EST 2008
Mike Meyer wrote:
> 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]
That's nice.
>
>> 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
For example, I thought the python "equivalent" of perl's foreach might be:
data_out = [[] foreach data_in]
Trying to answer my own question, if it comes down to a choice between a unique
statement v. the anonymous variable "_", then I guess I can see why Python did
it this way.
More information about the Python-list
mailing list