[Python-Dev] comprehension abbreviation (was: Adding any() and all())

"Martin v. Löwis" martin at v.loewis.de
Tue Mar 15 21:45:58 CET 2005

Eric Nieuwland wrote:
> The full syntax is:
>     [ f(x) for x in seq if pred(x) ]
> being allowed to write 'x' instead of 'identity(x)' is already a 
> shortcut, just as dropping the conditional part.

That's not the full syntax. The full syntax is

     [ <test> for <exprlist> in <testlist> <list-iter-opt> ]


<test> can be an arbitrary expression: and, or, lambda, +, -, ...
<exprlist> can be a list of expression, except for boolean and
relational expressions (but I think this is further constrained
<testlist> list a list of tests
<list-iter-opt> is optional, and can be another for or if block

So a more complex example is

    [ lambda a: a[x]+y*z for x,y in A for z in B if x > z]

(Not that this does what you think it does :-)

So that you can write f(x) is just a tiny special case.


More information about the Python-Dev mailing list