J
Jyotirmoy Bhattacharya
I'm a newcomer to Python. I have just discovered nested list
comprehensions and I need help to understand how the if-clause
interacts with the multiple for-clauses. I have this small program:
def multab(n):
print 'multab',n
return [n*i for i in range(5)]
print [(m,n) for m in range(5) for n in multab(m) if m>2]
It produces the output:
multab 0
multab 1
multab 2
multab 3
multab 4
[(3, 0), (3, 3), (3, 6), (3, 9), (3, 12), (4, 0), (4, 4), (4, 8), (4,
12), (4, 16)]
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.
comprehensions and I need help to understand how the if-clause
interacts with the multiple for-clauses. I have this small program:
def multab(n):
print 'multab',n
return [n*i for i in range(5)]
print [(m,n) for m in range(5) for n in multab(m) if m>2]
It produces the output:
multab 0
multab 1
multab 2
multab 3
multab 4
[(3, 0), (3, 3), (3, 6), (3, 9), (3, 12), (4, 0), (4, 4), (4, 8), (4,
12), (4, 16)]
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.