Go Premium for a chance to win a PS4. Enter to Win


Python Lambda functions

Posted on 2010-09-17
Medium Priority
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

Accepted Solution

1ce earned 1200 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 400 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 400 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: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say 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 http://docs.python.org/reference/expressions.html#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

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

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

Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
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 …
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
Suggested Courses

927 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