PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 5, 2022

[FIXED] What do the parenthesis following a lambda expression mean?

 November 05, 2022     function, lambda, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing