nested list comprehension and if clauses

Jyotirmoy Bhattacharya jmoy.matecon at gmail.com
Thu Jun 28 02:23:18 EDT 2007


On Jun 28, 10:53 am, a... at mac.com (Alex Martelli) wrote:
> Jyotirmoy Bhattacharya <jmoy.mate... at gmail.com> wrote:
> > print [(m,n) for m in range(5) for n in multab(m) if m>2]
> > I was wondering if there is some way to write the if-clause so that it
> > is 'hoisted' out of the inner loop and the multab function is not
> > called at all for m=0,1,2. That would seem to be important if multab
> > were an expensive function.

> Generally, the semantics of:
>
> x = [<expr> for <F1> if <I2> for <F3>]
>
> are exactly those of
>
> x = []
> for <F1> :
>   if <I2> :
>     for<F3> :
>       x.append(expr)
>

Thanks. That makes things completely clear to me.




More information about the Python-list mailing list