1

So, I was tinkering with list comprehensions, and the following surprised me:

>>> funs = [lambda x:x**i for i in range(10)]
>>> print [fun(2) for fun in funs]
[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]

How would I get:

>>> funs2 = [lambda x:x**0, lambda x:x**1, lambda x:x**2, lambda x:x**3, 
         lambda x:x**4, lambda x:x**5, lambda x:x**6, lambda x:x**7, 
         lambda x:x**8, lambda x:x**9]     
>>> print [fun(2) for fun in funs2]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

with list comprehensions, assuming such a thing is possible?

A. Berman
  • 19
  • 1
  • 1
    just do `lambda x,i=i:x**i`, it will grab that particular variable by name out of scope, but even better would be to actually read up on the topic and do it proper way :) – Tomasz Plaskota Jun 05 '17 at 14:48
  • Thanks, that works (and is more elegant than the solution in the linked version, `(lambda a: lambda x: x**a)(i)`). And thanks Ashwini, I hadn't noticed the one you linked. As for "the proper way", what would you say that is? I realize "a list of functions with variables in a range (or from a list or other iterable)" is of very marginal utility (as opposed to, say, a single function with another variable), but surely it's a valid construct? – A. Berman Jun 05 '17 at 14:55
  • Why do you even need lambda here? this is just `[2**i for i in range(10)]` – e4c5 Jun 05 '17 at 14:57
  • @e4c5 that was a toy example. I'm not trying to compute the first 10 powers of 2, it's just what I was playing with. I generally find strange structures like this surprisingly useful in some problems, though I don't have a specific example of where you'd want such a construct at the moment – A. Berman Jun 05 '17 at 14:59
  • Please don't waste everyone's time with toy examples https://stackoverflow.com/help/mcve http://stackoverflow.com/help/how-to-ask – e4c5 Jun 05 '17 at 15:01
  • @e4c5 thanks for the advice, I'll keep that in mind in the future. – A. Berman Jun 05 '17 at 15:03

0 Answers0