Issue
I am new to Python and I am wondering why this doesn't work for lambda:
for person in people:
print(lambda person:person.split()[0] + ' ' + person.split()[-1])
results:
<function <lambda> at 0x7f9d04332ed8>
<function <lambda> at 0x7f9d04332ed8>
<function <lambda> at 0x7f9d04332ed8>
<function <lambda> at 0x7f9d04332ed8>
But instead, the solution given was
for person in people:
print((lambda person:person.split()[0] + ' ' + person.split()[-1])(person))
Results:
Dr. Brooks
Dr. Collins-Thompson
Dr. Vydiswaran
Dr. Romero
What does it mean to add (person)
behind the lambda expression? And what does the first result mean?
Solution
A lambda
expression defines an anonymous function.
Like other functions, it doesn't do anything unless you call it.
I suspect that you might be confusing yourself by naming the lambda
parameter the same as the loop variable - they are entirely different things.
With unique naming, your code becomes
for person in people:
print(lambda p:p.split()[0] + ' ' + p.split()[-1])
for person in people:
print((lambda p:p.split()[0] + ' ' + p.split()[-1])(person))
which makes the difference clearer.
Note that the first version doesn't use the loop variable at all.
Even clearer is a version with a named function:
def the_function(p):
return p.split()[0] + ' ' + p.split()[-1]
# First attempt
for person in people:
print(the_function)
# Second attempt
for person in people:
print(the_function(person))
Answered By - molbdnilo Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.