0

Suppose I have a series of python function:

lam1 = lambda x: return x+1
lam2 = lambda x: return x+2
lam3 = lambda x: return x+3

And I would like to call them in this way:

x = lam1(x)
x = lam2(x)
x = lam3(x)

or so like this:

for lam in lams:
    x = lam(x)

This is helpful if I have a lot of functions to call, but this would have for loop. Do I have other way to do this without for loop?

5
  • 2
    you can not use return in lambda. Use this lam1 = lambda x: x+1 and not this lam1 = lambda x: return x+1 Commented Jul 25, 2019 at 7:41
  • without for loop or loop? You need some loop anyway. Commented Jul 25, 2019 at 7:42
  • what is your input and output. Commented Jul 25, 2019 at 7:49
  • Possible duplicate of Composing functions in python Commented Jul 25, 2019 at 7:51
  • 1
    post a real use case for your functions Commented Jul 25, 2019 at 7:55

1 Answer 1

1

One of possible solutions is to simply use one function in another, like this:

>>> lam1 = lambda x: x+1
>>> lam2 = lambda x: lam1(x)+2
>>> lam3 = lambda x: lam2(x)+3
>>> lam3(1)
7

Although i don't understand why you would want exactly that and no loops. This solution has the drawback of limited amount of functions one would care to construct in that way. Alternatively you can make a loop to create those functions like:

>>> from functools import partial
>>> oldLam = lambda x: x
>>> newLam = lambda x,lam,c: lam(x) + c
>>> for i in range(5):
    oldLam = partial(newLam, lam = oldLam, c = i)


>>> oldLam(1)
11

Unless it is also an illegal case for you...

Sign up to request clarification or add additional context in comments.

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.