for loop without variable

Carl Banks pavlovevidence at gmail.com
Fri Jan 11 00:34:07 EST 2008


On Thu, 10 Jan 2008 22:36:56 -0500, Marty wrote:
> 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?

Most languages that have "foreach" use it the same way Python uses 
"for".  The reason they use "foreach" instead of plain "for" is often 
because they have a separate for statement that mimic C's for.

Perhaps you're wondering why there is no syntax for looping a given 
number of times.  (Languages that have this feature, e.g., Ada, often to 
use "repeat" as the keyword.)

1. Looping a fixed number of times is quite uncommon.
2. A syntax for it buys you almost nothing.


Carl Banks



More information about the Python-list mailing list