nested list comprehension and if clauses

Paul Rubin http
Thu Jun 28 07:18:43 CEST 2007


Jyotirmoy Bhattacharya <jmoy.matecon at gmail.com> writes:
> 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.

Maybe you mean

 print [(m,n) for m in [a for a in range(5) if a > 2] for n in multab(m)]

You'd probably really write

  print [[(m,n) for m in range(3,5)] for n in multab(m)]

You should also use xrange instead of range, if the range might be
large.  And you could use a generator expression instead of a listcomp
for the inner list.



More information about the Python-list mailing list