Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Question about using lambda
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)   

<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)
ichabod801 wrote Aug-17-2019, 02:16 AM:
Please use python and output tags when posting code and results. I put them in for you this time. Here are instructions for doing it yourself next time.
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.
Craig "Ichabod" O'Brien -
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

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.


def f(x): return 2*x


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)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Life of Brian: Conjugate the verb, "to go" !
Just read this link a few days ago
5 common beginner mistakes in Python

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Newbie question to use lambda on multiple columns of a dataframe zydjohn 0 3,162 Jan-23-2018, 06:08 PM
Last Post: zydjohn
  Newbie lambda question Truman 6 1,332 Dec-11-2017, 11:21 PM
Last Post: Truman

Forum Jump:

Users browsing this thread: 1 Guest(s)