Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question about using lambda
#1
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)
Reply
#2
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 - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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.
Reply
#4
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)
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

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
Just read this link a few days ago
5 common beginner mistakes in Python
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple code question about lambda and tuples JasPyt 7 3,238 Oct-04-2021, 05:18 PM
Last Post: snippsat
  Newbie question to use lambda on multiple columns of a dataframe zydjohn 0 5,789 Jan-23-2018, 06:08 PM
Last Post: zydjohn
  Newbie lambda question Truman 6 4,845 Dec-11-2017, 11:21 PM
Last Post: Truman

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020