Python Forum

Full Version: Question about using lambda
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I just wrong across this "anonymous function" named lambda and have a quick question.

Why am I getting the lambda error message with this code:
r = lambda x, y: x * y
r(12, 3)   
print(r)

<function <lambda> at 0x00000199699B5168>
but not with this code (where I assign the arguments to a variable):
r = lambda x, y: x * y
multiply_it = r(12, 3)
print(multiply_it)
Note that in the second case you are not assigning the arguments (12 and 3) to a variable, your are assigning the return value (36) to a variable. In the first case, you don't assign the result (return value) of r(12, 3) to anything, so it just disappears. Functions don't store their return value. When you print r, it just prints the function object, which is just a note that r is a lambda function stored at a particular address.
Also note that the first case is not an error message. You are literally asking python to display a function, not the result of a function. This is what Python does, it outputs a message telling you that it is outputting a lambda function and giving you its memory address.
For recommended practice look at PEP8 - Style Guide for Python Programming - Programming Recommendations

Quote:Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.

Yes:

def f(x): return 2*x

No:

f = lambda x: 2*x

The first form means that the name of the resulting function object is specifically 'f' instead of the generic '<lambda>'. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)
Just read this link a few days ago
5 common beginner mistakes in Python