0

Is there any way how to code recursive function containing if with lamba? Is possible to rewrite this using lambda.

def factorial(x):
    if x <= 1:
        return 1
    return x * factorial(x - 1)

print(factorial(5)) 
4
  • Why do you feel the need to do that? Commented Jan 3, 2015 at 21:09
  • just asking if it's possible Commented Jan 3, 2015 at 21:10
  • Dear @BrenBarn I was asking if is possible to use if statements in lambda. Commented Jan 3, 2015 at 21:21
  • @gml: In that case, you have your answer below. It is not possible to use any statements in a lambda. Commented Jan 3, 2015 at 21:26

3 Answers 3

4

No, or at least not without assigning the function to a variable and then using that name to call it. But you still cannot use any statements in the function.

In any case, don't do that. A lambda function is exactly like a normal def function in Python besides the restriction that it cannot contain statements.

The only reason to use a lambda in Python is to avoid defining an named function if you just need a simple callable returning some value.

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

4 Comments

what about >>> fa= lambda x :1 if x <= 1 else x*fa(x-1) ?
@Kasra - That's different. There are no statements in the code you posted (except for the assignment of course). The OP was asking if he can put a statement in a lambda, which is not possible.
Updated my answer to mention this case.
@iCodez ohum , yep , i think so !
2

Yes, it is possible for this specific case.

>>> factorial = lambda x: 1 if x < 1 else x * factorial(x - 1)
>>> factorial(5)
120

I wouldn't recommend it though. A standard function definition seems far more readable to me.

Comments

2
>>> l = lambda i: 1 if i<=1 else i * l(i-1)
>>> l(5)
120
>>> 5*4*3*2*1
120

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.