# For loop extended syntax

Kay Schluehr kay.schluehr at gmx.net
Mon Mar 21 07:23:36 CET 2005

```George Sakkis wrote:

> > Looks very appealing, but what to do with
> >
> > [x*y-z for (x=0,y,z) in (1,2,3), (4,5), (6,7,8)] ?
> >
> > Should it raise an exception due to a pattern mismatch?
>
> I didn't have in mind to generalize the syntax even more than the
respective
> for function
> signatures, therefore this would be syntax error:
> SyntaxError: non-keyword arg after keyword arg

O.K. Allthough it has fallen out of Guidos favor one can use a lambda
to obtain the same solution:

[(lambda x,y,z=0:x*y-z)(*vec) for vec in (1,2,3), (4,5), (6,7,8)]

This inspires to examine Your list comprehension not as plain 'syntax
suggar' but in a clear operational perspective. Since (x,y,z=0) is not
a valid Python tuple we have to replace it by

lambda x,y,z=0:(x,y,z)

This acts on the list elements of the comprehension like the proposed
(x,y,z=0) whereas the valid (x,y,z) acts like

lambda x,y,z:(x,y,z)

So we have generalized tuples to lambdas. If we let lambda
x,y,z=0:(x,y,z) iterate over the list elements, why not the generalized

lambda x,y,z=0:(lambda x,a=0:(x,a),y,z) ?

Returning to Your soluion and translating back the lambda:

[x*y-z for ((x,a=0),y,z=0) in (1,2,3), (4,5), (6,7,8)]

should also be possible from an operational perspective.

Regards Kay

```