0

Is it possible to replace any lambda function with normal function?

 e.g. lst1 = [lambda x:x*i for i in range(5)]
      lst2 = [j(2) for j in lst1]

Here can we use normal function in stead of lambda?

If it's possible then please tell how to do the same.

Thanks!

user2550098
  • 163
  • 1
  • 13
  • It is always possible. A lambda is just a simple one-line function. What is confusing you? – Daniel Roseman Apr 28 '16 at 09:27
  • Note that with `[lambda x:x*i for i in range(5)]` you will run into classic [What do (lambda) function closures capture in Python?](http://stackoverflow.com/questions/2295290/what-do-lambda-function-closures-capture-in-python) problem. – Ashwini Chaudhary Apr 28 '16 at 09:36
  • @DanielRoseman Can you please convert above example replacing lambda with normal function. I am not getting how to do that. – user2550098 Apr 28 '16 at 09:54

2 Answers2

2

Yes you can using functools.partial:

from functools import partial

def fun(x, i):
    return x * i

lst1 = [partial(fun, i=i) for i in range(5)]
lst2 = [j(2) for j in lst1]
AKS
  • 18,983
  • 3
  • 43
  • 54
  • 1
    2 sec quicker, but i guess this is the answer the OP waits for! – Colonel Beauvel Apr 28 '16 at 09:35
  • OP's `lst2` does print `[8, 8, 8, 8, 8]` however because `i` is 4 at the end of the loop but I don't think that's what he wants. – AKS Apr 28 '16 at 09:39
  • Hey thanks AKS, but output are different. Can we change it have same o/p i.e [8, 8, 8, 8, 8] ? I was not knowing this partial concept. Thanks for that :) – user2550098 Apr 28 '16 at 09:57
  • 1
    If you just want `[8, 8, 8, 8, 8]` you could use `[8] * 5`. – AKS Apr 28 '16 at 10:14
1

yes - lambda is actually "make function"; you will need to give it a name

lst1 = [lambda x:x*i for i in range(5)]

def replace_lambda(x):
    return x * x

lst2 = [replace_lambda for i in range(5)]

print lst1
print lst2

for idx, func in enumerate(lst1):
    print func(idx)

for idx, func in enumerate(lst2):
    print func(idx)

result:

[<function <lambda>>, <function <lambda>>, <function <lambda>>, <function <lambda>>, <function <lambda>>]
[<function replace_lambda>, <function replace_lambda>, <function replace_lambda>, <function replace_lambda>, <function replace_lambda>]
0
1
4
9
16
0
1
4
9
16
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80