Python Lambda functions

Posted on 2010-09-17
Last Modified: 2012-08-14
I have a question regarding lambda functions in python. I made this general because this involves a homework assignment.

I call a function, lets say:

command prompt (ipython)>>>a = [1,2,3]
command prompt (ipython)>>>b = [1,2,3]
command prompt (ipython)>>> thingy(lambda a: a == b)

def thingy(hello):
    (if hello is true):
         return []
   return "EPIC FAIL"

So here's the question... I HAVE NO IDEA how to test if HELLO IS TRUE within the function.

Python is new to me and I don't know much about booleans. Right now I have in place of "(if hello is true)" -- "if hello is True:"

This is not working correctly!! It doesn't return correctly. Any help would be great!
Question by:jeffiepoo
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Accepted Solution

1ce earned 300 total points
ID: 33705994

def thingy(hello):
    if hello:
        return ""
    return "EPIC FAIL"
compare = lambda x,y: x == y

a = [1,2,3]
b = [1,5,3]

for i in [0,1,2]:
    print str(i) + thingy(compare(a[i],b[i]))
LVL 29

Assisted Solution

pepr earned 100 total points
ID: 33708957
Generally, if v is a boolean variable, then

    if v is True:


    if v == True:

or the like is a kind of not nice or confusing way of testing.  The "if" expects the boolean condition (the boolean result of an expression).  Put the constant values instead of v and you can see:

    if True is True:
    if False is True:
    if True == True:
    if False == True:

Or you can go to the verbal extreme:

    if (v does not hold) does hold:                  # this is not abou the syntax which is not acceptable by Python

1ce shows the way how it should be done.  In my opinion, the key point to fix the code also is to replace the "hello" identifier to something more meaningfull.

Assisted Solution

-Richard- earned 100 total points
ID: 33716172
I"ll throw in my two-cents worth too.  .  

I think you are not real clear on what lambda functions really are.  They are "anonymous" functions which the "lambda" keyword allows you to define without ever giving it a name.  The anonymous function thusly defined will always accept as a parameter the variable (or comma-separated list of variables) on the left of the colon, and will always return as a value the expression on the right side of the colon.  Thus you can think of this expression:

        myfunc = lambda x: x == 2
as being equivalent to        

        def anonymous(x):
                return x == 2
        myfunc = anonymous
This creates a function named "myfunc" that accepts one parameter and tests if that parameter is 2.  Note that no function called "anonymous" is ever actually created - but you can think of what's happening as if it was.

At this point, if you want to evaluate this function, you would do so by calling myfunc and passing it a parameter:

        x = 1
        if (myfunc(x)):
                print "X is 2"
                print "X is not 2"

(prints "X is not 2")

So in your original example, your lambda expression defines a function that takes one parameter.  As a result, strictly speaking, the direct answer to your original question, "how do I test if hello is true within the function", is this:  you must pass hello a single parameter for it to evaluate.  Thus in your original sample code, strictly speaking you would need to change it to:

        def thingy(hello):
                if hello('SOME PARAMETER GOES HERE'):
                        return []
                return "EPIC FAIL"
However, "thingy's" problems go deeper that that, because as defined, you don't have any parameter to pass to hello inside thingy.  This is what led to 1ce's solution where he defines a lambda with 2 parameters; then he actually evaluates that lambda prior to calling thingy, which in his version does nothing but test the result, circumventing the issue of what parameters to pass to "hello" from inside "thingy".
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.


Expert Comment

ID: 33719839
I'll add one further note - you say that currently thingy is written as "if hello is True:".  This will not work because, since you are failing to supply a parameter to hello, the Python interpreter understands the "hello" as referring to the function object itself, rather than a call to it.  That statement would therefore test whether the function reference passed in is identical to the value True, which it never is, so that statement would simply fail the test every time.  
LVL 29

Expert Comment

ID: 33722512
Richard is completely right.  If the hello was used without anything (i.e. "if hello: ..."), then the function object would be evaluated as expression in the boolean context as True -- see the doc 5.10. Boolean operations which says:

"In the context of Boolean operations, and also when expressions are used by  control flow statements, the following values are interpreted as false: False, None, numeric zero of  all types, and empty strings and containers (including strings, tuples, lists,  dictionaries, sets and frozensets). All other values are interpreted as true.  (See the __nonzero__() special method for a way to change  this.)"

In your original question, you should not put parentheses around the if command.  The parentheses are not neccessary even around the boolean condition (unlike in C-family languages).  The constants for the boolean type are True and False with capital letters.  As Richard said, after correcting that (as he has shown) you will always get the  "EPIC FAIL".  Try the following interactive example:

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a == b
>>> (lambda a: a == b)
<function <lambda> at 0x000000000203D828>
>>> bool(lambda a: a == b)
>>> b = []
>>> bool(lambda a: a == b)

The bool() function returns the boolean value of whatever object is passed in.  It returns the same value that would be evaluated in a boolean context.  As the doc (above says), the function object does not fall into category of things evaluated as False.  It is always evaluated as True.  However, the operator "is" does not introduce a boolean context.  It compares the object that represents the lambda function with the object that represents the constant True.

This way, 1ce changed the testing to use the boolean context evaluation (always True), Richard shown that using "hello is True" will evaluate always to False for the lambda function.
LVL 29

Expert Comment

ID: 33722526
If in doubt, leave the lambda out.  It is sometimes easier to understand the things without lambda calculus functions (at least for beginners).

Expert Comment

ID: 33725770
So just to wrap it up in a neat package, here's is a way to implement your sample program which evaluates your lambda function to compare a and b from within thingy, obtaining parameters to pass it from the user.   I'm using your naming conventions so you can see more easily the relation of this program to the original, but as my esteemed colleague Pepr has pointed out, you really should come up with more descriptive names.  

def thingy( hello):
    left = input("Enter left side of comparison: ")
    right = input("Enter right side of comparison: ")
    if hello( left, right):
        print "They are equal."
        print "They are not equal"

>>> thingy( lambda a,b: a == b)
Enter left side of comparison: [1,2,3]
Enter right side of comparison: [1,2,3]
They are equal
>>> thingy( lambda a,b: a==b)
Enter left side of comparison: "hello"
Enter right side of comparison: "world"
They are not equal

Some notes:  

The "input" statement expects a Java object, so strings must be entered with quotes around them, otherwise you'll get an exception.  For clarity I didn't put exception handling in.

Also note that in the lambda expression, there is no need for the program to define "a" and "b" prior to running thingy, as you had attempted to do in your original sample.  Those are purely syntactical placeholders used in the definition of the anonymous function.  

Author Closing Comment

ID: 33740063
Thanks guys

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

"The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question