Python Forum
Question about using lambda - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Question about using lambda (/thread-20538.html)



Question about using lambda - hikerguy62 - Aug-17-2019

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)



RE: Question about using lambda - ichabod801 - Aug-17-2019

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.


RE: Question about using lambda - boring_accountant - Aug-17-2019

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.


RE: Question about using lambda - perfringo - Aug-17-2019

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)



RE: Question about using lambda - ThomasL - Aug-18-2019

Just read this link a few days ago
5 common beginner mistakes in Python