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!

3
  • It is always possible. A lambda is just a simple one-line function. What is confusing you? Commented Apr 28, 2016 at 9: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? problem. Commented Apr 28, 2016 at 9:36
  • @DanielRoseman Can you please convert above example replacing lambda with normal function. I am not getting how to do that. Commented Apr 28, 2016 at 9:54

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

4 Comments

2 sec quicker, but i guess this is the answer the OP waits for!
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.
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 :)
If you just want [8, 8, 8, 8, 8] you could use [8] * 5.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.