'What do the parenthesis following a lambda expression mean?
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 1:[1]
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))
Solution 2:[2]
A lambda is a function. Yours might be written like this:
lambda person:person.split()[0] + ' ' + person.split()[-1]
But it's the same as this:
def myLambda(person):
return person.split()[0] + ' ' + person.split()[-1]
And of course both need to be called. To call the function one would use its name, followed by parenthesis: myLambda()
but you didn't allocate a name to the lambda function. Instead, by wrapping it in parenthesis, we get a function. You can then put parenthesis on the end to call it:
# ------------ lambda function is in parenthesis -----------##-and then called with the `person` variable
(lambda person:person.split()[0] + ' ' + person.split() [-1])(person)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | LaytonGB |