rec_fn = lambda: 10==11 or rec_fn()
rec_fn()
I am new to Python and trying to understand how lambda expressions work. Can somebody explain how this recursion is working? I am able to understand that 10==11 will be 'false' and that's how rec_fn will be called again and again recursively.
But what I am not able to get is this seemingly new way of writing a lambda expression.
whatever happened to lambda x: x+y where there is a parameter 'x' going into the unnamed function?
Also, why is
rec_fn() = lambda: .... // a syntax error
rec_fn = lambda: .... //syntactically correct - WHY?
What is rec_fn? Is it a function or a variable?
It may help to think of a function call as an operator. Because that's what it is. When you do rec_fn() you are doing two things. First, you're getting a reference to the object named rec_fn. This happens to be a function, but that doesn't matter (in Python, objects besides functions are callable). Then there is () which means "call the object I just named." It is possible to get a reference to a function without calling it, just by leaving off the parentheses, and then you can assign it different names, any of which can then be used to call it by adding the parentheses.
def func1():
print "func1"
func2 = func1
func2() # prints "func1"
Now you can see how the lambda works.
func3 = lambda x: x+1
You are doing the same as the func2 = func1 line above, except the lambda expression is the function. The syntax is just different; the lambda function can be defined without giving it a name.
Lambdas can have any number of parameters, so lambda: 3 is a function that takes no parameters and always returns 3, while lambda x, y: x+y is a function that takes two parameters and returns their sum.
As to the way or is being used, it's taking advantage of short-circuiting. Basically, or knows that if its first operand is True, it doesn't need to evaluate the second, because the result is going to be True regardless of what the second argument is. You could thus read this as if not 10==11: rec_fn(). By the way, and also short-circuits, although it does so if the first argument is False since it knows that the result will be False regardless of what the second argument is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With