Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can i use two or more lambda in one function

imagine i have a function like this

def func(x):
    a = lambda b : x + b
    a = lambda c : a * c
    return a;

how can i give argument to second lambda. is this even possible btw?
and i was thinking is there any way to give one argument and b, c both use that arg?

i tried to pass parameters one by one like this:
(i want print(a(6)) to print 60)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

myFunc = func(4);
a = myFunc(6)
print(a(6));

and i end up with this error :

line 4, in <lambda>
    a = lambda c : a * c
TypeError: unsupported operand type(s) for *: 'function' and 'int'

>Solution :

The error you encountered is due to the fact that you are trying to perform the multiplication operation between a lambda function (a) and an integer (c). In Python, you cannot directly multiply a function with an integer.

To achieve what you want, you can create a single lambda function with two arguments (b and c) and return their sum and product, like this:

def func(x):
  a = lambda b, c: (x + b, x * c)
  return a

Now, you can call the func function and then the returned lambda function with two arguments:

myFunc = func(4)
result_sum, result_product = myFunc(6, 6)
print("Sum:", result_sum)       # Output: Sum: 10 (4 + 6)
print("Product:", result_product)  # Output: Product: 24 (4 * 6)

Here, we define a lambda function with two arguments b and c, and we return a tuple containing their sum and product. By doing this, you can use a single lambda function to compute both the sum and the product of the input values.

If you need to keep the intermediate results and use them in subsequent operations, you can store them in variables and pass them to the lambda function as needed. However, the lambda function itself can only take the arguments specified in its definition.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading