[Python-ideas] Function to unnest for-statements

Neil Toronto ntoronto at cs.byu.edu
Fri May 23 10:19:29 CEST 2008


Carl Johnson wrote:
> So, going back to the first example, wouldn't it be nicer to write:
> 
> for x, y, z in combine(xs, ys, zs):
>    #Do something
> 
> If nothing else, this has the advantage that if you don't have to nest 
> the for-loops, things don't end up being so deeply indented on the screen.

FWIW, I find myself doing this often with numpy:

     for index in numpy.ndindex(arr.shape):
         # do something using arr's indexes, whatever they are

(Broadcasting is better, but sometimes this is unavoidable.)

The point is there's a general use-case Carl left out: what if you don't 
know how deeply you'll need to nest? Our Functional friends know the 
answer to this, but IIRC the Python design philosophy doesn't actively 
encourage recursive solutions.

I don't think the use-cases are common enough to warrant a new builtin 
(though that's just my $0.000001 opinion - it may be that *everyone* 
will want to flatten their nested loops), but something like "combine" 
would fit very well into itertools.

Neil




More information about the Python-ideas mailing list