question about what lamda does

Discussion in 'Python' started by nephish@xit.net, Jul 18, 2006.

  1. Guest

    Hey there,
    i have been learning python for the past few months, but i can seem to
    get what exactly a lamda is for. What would i use a lamda for that i
    could not or would not use a def for ? Is there a notable difference ?
    I only ask because i see it in code samples on the internet and in
    books.

    thanks for any clarity

    sk
     
    , Jul 18, 2006
    #1
    1. Advertising

  2. Dan Bishop Guest

    wrote:
    > Hey there,
    > i have been learning python for the past few months, but i can seem to
    > get what exactly a lamda is for.


    It defines a function.

    f = lambda x, y: expression

    is equivalent to

    def f(x, y):
    return expression

    Note that lambda is an expression while def is a statement.

    > What would i use a lamda for that i
    > could not or would not use a def for ? Is there a notable difference ?
    > I only ask because i see it in code samples on the internet and in
    > books.


    Lambdas are typically used as parameters to functions that take
    functions as arguments, like property() and reduce(). You never *need*
    to use one, but sometimes it's convenient.
     
    Dan Bishop, Jul 18, 2006
    #2
    1. Advertising

  3. Guest

    ok, i think i get it.
    pretty cool.
    thanks
    -sk


    Dan Bishop wrote:
    > wrote:
    > > Hey there,
    > > i have been learning python for the past few months, but i can seem to
    > > get what exactly a lamda is for.

    >
    > It defines a function.
    >
    > f = lambda x, y: expression
    >
    > is equivalent to
    >
    > def f(x, y):
    > return expression
    >
    > Note that lambda is an expression while def is a statement.
    >
    > > What would i use a lamda for that i
    > > could not or would not use a def for ? Is there a notable difference ?
    > > I only ask because i see it in code samples on the internet and in
    > > books.

    >
    > Lambdas are typically used as parameters to functions that take
    > functions as arguments, like property() and reduce(). You never *need*
    > to use one, but sometimes it's convenient.
     
    , Jul 18, 2006
    #3
  4. Use it anywhere a quick definition of a function is needed that can be
    written as an expression. For example when a callback function is
    needed you could say:
    def callback(x,y):
    return x*y
    some_function(when_done_call_this=callback)
    But with lambda you could just write
    some_function(when_done_call_this=lambda x,y:x*y)
    Note: because it is an _expression_ you cannot do stuff like 'if..else'
    inside of lambda.

    -Nick V.

    wrote:
    > Hey there,
    > i have been learning python for the past few months, but i can seem to
    > get what exactly a lamda is for. What would i use a lamda for that i
    > could not or would not use a def for ? Is there a notable difference ?
    > I only ask because i see it in code samples on the internet and in
    > books.
    >
    > thanks for any clarity
    >
    > sk
     
    Nick Vatamaniuc, Jul 18, 2006
    #4
  5. Guest

    so a lamda needs to stay at one expression, and use more than one lamda
    for more expressions ?

    i think i get it.

    sk

    Nick Vatamaniuc wrote:
    > Use it anywhere a quick definition of a function is needed that can be
    > written as an expression. For example when a callback function is
    > needed you could say:
    > def callback(x,y):
    > return x*y
    > some_function(when_done_call_this=callback)
    > But with lambda you could just write
    > some_function(when_done_call_this=lambda x,y:x*y)
    > Note: because it is an _expression_ you cannot do stuff like 'if..else'
    > inside of lambda.
    >
    > -Nick V.
    >
    > wrote:
    > > Hey there,
    > > i have been learning python for the past few months, but i can seem to
    > > get what exactly a lamda is for. What would i use a lamda for that i
    > > could not or would not use a def for ? Is there a notable difference ?
    > > I only ask because i see it in code samples on the internet and in
    > > books.
    > >
    > > thanks for any clarity
    > >
    > > sk
     
    , Jul 18, 2006
    #5
  6. Guest

    The two primary differences between using def and using lambda is that
    lambda is limited to a single expression and def cannot be used within
    another function.

    Basically, use lambda when you need to define a small function within
    another function. I've also used it to create 'shortcut' functions as:

    bar = lambda a, b: object1.object2.function1( a ).function2( b )
    foo = bar( somevalue1, somevalue2 )

    It can save you a lot of typing if used wisely, and makes your code
    smaller and neater too :)

    On a real world example:

    import random
    roll_die = lambda sides=6: random.choice( range(1,sides+1) )
    # roll dies with 4, 6, and 20 sides
    print roll_die(4), roll_die(), roll_die(20)


    Have fun with your lambdas.

    greb

    wrote:
    > Hey there,
    > i have been learning python for the past few months, but i can seem to
    > get what exactly a lamda is for. What would i use a lamda for that i
    > could not or would not use a def for ? Is there a notable difference ?
    > I only ask because i see it in code samples on the internet and in
    > books.
    >
    > thanks for any clarity
    >
    > sk
     
    , Jul 18, 2006
    #6
  7. K.S.Sreeram Guest

    wrote:
    > The two primary differences between using def and using lambda is that
    > lambda is limited to a single expression and def cannot be used within
    > another function.


    'def' can certainly be used within another function :

    def make_adder( delta ) :
    def adder( x ) :
    return x + delta
    return adder

    [sreeram;]


    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.2.2 (MingW32)
    Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

    iD8DBQFEvQNjrgn0plK5qqURAjQxAKCMz0WV/0ZAfW/en4IVHGMztxzWdQCgrYWH
    rOS510r1w1GTDB+5Nqj1cFQ=
    =ISgg
    -----END PGP SIGNATURE-----
     
    K.S.Sreeram, Jul 18, 2006
    #7
  8. Steve Holden Guest

    wrote:
    > The two primary differences between using def and using lambda is that
    > lambda is limited to a single expression and def cannot be used within
    > another function.
    >

    Where on earth did you get that from? I presume you mean "You can't use
    a def statement as an argument to a function"?

    There is nothing wrong with

    def adder(x):
    def func(y):
    return x+y
    return func

    for example. Then adder(5) returns a function that returns 5 more than
    its argument.

    regards
    Steve
    --
    Steve Holden +44 150 684 7255 +1 800 494 3119
    Holden Web LLC/Ltd http://www.holdenweb.com
    Skype: holdenweb http://holdenweb.blogspot.com
    Recent Ramblings http://del.icio.us/steve.holden
     
    Steve Holden, Jul 18, 2006
    #8
  9. tac-tics Guest

    wrote:
    > Hey there,
    > i have been learning python for the past few months, but i can seem to
    > get what exactly a lamda is for. What would i use a lamda for that i
    > could not or would not use a def for ? Is there a notable difference ?
    > I only ask because i see it in code samples on the internet and in
    > books.


    Lambda is just as powerful as a function, but totally useless =-P

    Lambda used to be handy before the introduction of list comprehensions.
    Now, though, there primary use is obfuscating your code.
     
    tac-tics, Jul 18, 2006
    #9
  10. Guest

    I stand corrected. Not sure where I got that from, improper
    defragmentation due to sleep depravation perhaps...

    K.S.Sreeram wrote:
    > wrote:
    > > The two primary differences between using def and using lambda is that
    > > lambda is limited to a single expression and def cannot be used within
    > > another function.

    >
    > 'def' can certainly be used within another function :
    >
    > def make_adder( delta ) :
    > def adder( x ) :
    > return x + delta
    > return adder
    >
    > [sreeram;]
    >
    >
    > --------------enigFDB411206B54B101CC680F5A
    > Content-Type: application/pgp-signature
    > Content-Disposition: inline;
    > filename="signature.asc"
    > Content-Description: OpenPGP digital signature
    > X-Google-AttachSize: 253
     
    , Jul 18, 2006
    #10
  11. Steve Holden Guest

    tac-tics wrote:
    > wrote:
    >
    >>Hey there,
    >>i have been learning python for the past few months, but i can seem to
    >>get what exactly a lamda is for. What would i use a lamda for that i
    >>could not or would not use a def for ? Is there a notable difference ?
    >>I only ask because i see it in code samples on the internet and in
    >>books.

    >
    >
    > Lambda is just as powerful as a function, but totally useless =-P
    >
    > Lambda used to be handy before the introduction of list comprehensions.
    > Now, though, there primary use is obfuscating your code.
    >

    I do wish you could hold yourself back and stop muddying the waters.
    Lambdas and list comprehensions have little or nothing to do with each
    other. Unless you know something I don't ...

    regards
    Steve
    --
    Steve Holden +44 150 684 7255 +1 800 494 3119
    Holden Web LLC/Ltd http://www.holdenweb.com
    Skype: holdenweb http://holdenweb.blogspot.com
    Recent Ramblings http://del.icio.us/steve.holden
     
    Steve Holden, Jul 19, 2006
    #11
  12. Iain King Guest

    Steve Holden wrote:
    > tac-tics wrote:
    > > wrote:
    > >
    > >>Hey there,
    > >>i have been learning python for the past few months, but i can seem to
    > >>get what exactly a lamda is for. What would i use a lamda for that i
    > >>could not or would not use a def for ? Is there a notable difference ?
    > >>I only ask because i see it in code samples on the internet and in
    > >>books.

    > >
    > >
    > > Lambda is just as powerful as a function, but totally useless =-P
    > >
    > > Lambda used to be handy before the introduction of list comprehensions.
    > > Now, though, there primary use is obfuscating your code.
    > >

    > I do wish you could hold yourself back and stop muddying the waters.
    > Lambdas and list comprehensions have little or nothing to do with each
    > other. Unless you know something I don't ...
    >


    I think he meant that lambda's main use before was inside map and
    filter; as stated earlier in the thread, lambda's main use was for
    passing simple functions as arguments, and of these map and filter must
    have made up a majority (and then I'd guess TKinter would be next).
    List comprehensions replace map and filter, so...

    I wouldn't put it as explosively as he has, but I find a lambda less
    clear than a def too.

    Iain


    > regards
    > Steve




    > --
    > Steve Holden +44 150 684 7255 +1 800 494 3119
    > Holden Web LLC/Ltd http://www.holdenweb.com
    > Skype: holdenweb http://holdenweb.blogspot.com
    > Recent Ramblings http://del.icio.us/steve.holden
     
    Iain King, Jul 19, 2006
    #12
  13. danielx Guest

    wrote:
    > Hey there,
    > i have been learning python for the past few months, but i can seem to
    > get what exactly a lamda is for. What would i use a lamda for that i
    > could not or would not use a def for ? Is there a notable difference ?
    > I only ask because i see it in code samples on the internet and in
    > books.
    >
    > thanks for any clarity
    >
    > sk


    hehe. Lambda's are kind of a sensative subject for pythoners who come
    from Lisp. Guido being more of a C guy doesn't really like them, and
    thought they should be removed in py3k. Last time I checked, he was
    reconsidering because of public outcry, presumably from the Lisp crowd.

    The standard reason for getting rid of it is "anywhere you need a
    lambda, you can use a def". In addition to what has been said here,
    there is another one small difference between lambda's and functions,
    which is that when you use def, the object gets a name:

    >>> def foo(): pass

    ....
    >>> foo

    <function foo at 0x009D8230>
    # ^ foo knows its own name
    >>> bar

    <function foo at 0x009D8230>
    # ^ see ;)
    >>>


    Whereas, a lambda has no name; it's "anonymous":

    >>> spam = lambda: 1
    >>> spam

    <function <lambda> at 0x009D80F0>
    # ^ spam has an identity crisis ;)
    >>>


    Many people who do not come from Lisp do not understand what the use of
    a lambda is (and I have no idea what the purpose of having a name is).
    Even people who do question whether it belongs in Python. In Lisp,
    lambda's are the way things get done, because you can calculate
    anything using just defines and expressions. This style does not fit
    Python very well, since we do things using statements.

    Python's lambda really can't be as powerful as Lisp's because Python
    does not have expressions that do case analysis (this is not lambda's
    fault, of course ;). The reason is that you really want to put each
    case on its own set of lines. This enhances readability at the expense
    of terseness. Since Python's statements are terminated by a newline, it
    would be rather awkward to have a kind of expression where good style
    calls for it to be spread out accross multiple lines.

    You can try to simulate these kinds expressions using into a list or
    dictionary, but this becomes rather messy. I think the only way to get
    this done properly is to use eval. For example:

    def recursiveFunction(args):
    ... # do stuff...
    choices = { True:"0", False:"recurisveFunction(newArgs)" }
    return eval( choices[predicate] )

    The reason that you need eval is that you want to prevent any cases
    from being executed until you decide which one you want. This stay of
    execution is accomplished by wrapping quotes around our expressions.
    This example illustrates why we really need this kind of behavior,
    because without it, we would fall into an infinite loop. Even if it
    were safe to evaluate all cases, it's a big waste of time to do so.

    Lastly, I think there is also a performance concern for certain uses of
    lambda (correct me if I'm wrong). Say you have an expression with a
    lambda in it where you could have used a def. Every time you evaluate
    that expression, you have to construct a new lambda object, which takes
    time. If you had used a def instead, you could hav avoided having to
    construct multiple times.
     
    danielx, Jul 20, 2006
    #13
  14. Guest

    hey thanks for that last post, although some of it was a bit over my
    head.
    i think i am getting more of the differences here.

    thanks again,
    sk

    danielx wrote:
    > wrote:
    > > Hey there,
    > > i have been learning python for the past few months, but i can seem to
    > > get what exactly a lamda is for. What would i use a lamda for that i
    > > could not or would not use a def for ? Is there a notable difference ?
    > > I only ask because i see it in code samples on the internet and in
    > > books.
    > >
    > > thanks for any clarity
    > >
    > > sk

    >
    > hehe. Lambda's are kind of a sensative subject for pythoners who come
    > from Lisp. Guido being more of a C guy doesn't really like them, and
    > thought they should be removed in py3k. Last time I checked, he was
    > reconsidering because of public outcry, presumably from the Lisp crowd.
    >
    > The standard reason for getting rid of it is "anywhere you need a
    > lambda, you can use a def". In addition to what has been said here,
    > there is another one small difference between lambda's and functions,
    > which is that when you use def, the object gets a name:
    >
    > >>> def foo(): pass

    > ...
    > >>> foo

    > <function foo at 0x009D8230>
    > # ^ foo knows its own name
    > >>> bar

    > <function foo at 0x009D8230>
    > # ^ see ;)
    > >>>

    >
    > Whereas, a lambda has no name; it's "anonymous":
    >
    > >>> spam = lambda: 1
    > >>> spam

    > <function <lambda> at 0x009D80F0>
    > # ^ spam has an identity crisis ;)
    > >>>

    >
    > Many people who do not come from Lisp do not understand what the use of
    > a lambda is (and I have no idea what the purpose of having a name is).
    > Even people who do question whether it belongs in Python. In Lisp,
    > lambda's are the way things get done, because you can calculate
    > anything using just defines and expressions. This style does not fit
    > Python very well, since we do things using statements.
    >
    > Python's lambda really can't be as powerful as Lisp's because Python
    > does not have expressions that do case analysis (this is not lambda's
    > fault, of course ;). The reason is that you really want to put each
    > case on its own set of lines. This enhances readability at the expense
    > of terseness. Since Python's statements are terminated by a newline, it
    > would be rather awkward to have a kind of expression where good style
    > calls for it to be spread out accross multiple lines.
    >
    > You can try to simulate these kinds expressions using into a list or
    > dictionary, but this becomes rather messy. I think the only way to get
    > this done properly is to use eval. For example:
    >
    > def recursiveFunction(args):
    > ... # do stuff...
    > choices = { True:"0", False:"recurisveFunction(newArgs)" }
    > return eval( choices[predicate] )
    >
    > The reason that you need eval is that you want to prevent any cases
    > from being executed until you decide which one you want. This stay of
    > execution is accomplished by wrapping quotes around our expressions.
    > This example illustrates why we really need this kind of behavior,
    > because without it, we would fall into an infinite loop. Even if it
    > were safe to evaluate all cases, it's a big waste of time to do so.
    >
    > Lastly, I think there is also a performance concern for certain uses of
    > lambda (correct me if I'm wrong). Say you have an expression with a
    > lambda in it where you could have used a def. Every time you evaluate
    > that expression, you have to construct a new lambda object, which takes
    > time. If you had used a def instead, you could hav avoided having to
    > construct multiple times.
     
    , Jul 20, 2006
    #14
  15. danielx wrote:
    (snip)

    > Python's lambda really can't be as powerful as Lisp's because Python
    > does not have expressions that do case analysis (this is not lambda's
    > fault, of course ;). The reason is that you really want to put each
    > case on its own set of lines. This enhances readability at the expense
    > of terseness. Since Python's statements are terminated by a newline, it
    > would be rather awkward to have a kind of expression where good style
    > calls for it to be spread out accross multiple lines.
    >
    > You can try to simulate these kinds expressions using into a list or
    > dictionary, but this becomes rather messy. I think the only way to get
    > this done properly is to use eval. For example:
    >
    > def recursiveFunction(args):
    > ... # do stuff...
    > choices = { True:"0", False:"recurisveFunction(newArgs)" }
    > return eval( choices[predicate] )


    Why do you want to use eval here ?

    > The reason that you need eval is that you want to prevent any cases
    > from being executed until you decide which one you want.


    What about:

    def recursiveFunction(args):
    ... # do stuff...
    ... # that defines 'newArgs' and 'predicate' of course ...
    return (recursiveFunction, lambda x: 0)[predicate](newArgs)

    --
    bruno desthuilliers
    python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
    p in ''.split('@')])"
     
    Bruno Desthuilliers, Jul 20, 2006
    #15
  16. danielx Guest

    Bruno Desthuilliers wrote:
    > danielx wrote:
    > (snip)
    >
    > > Python's lambda really can't be as powerful as Lisp's because Python
    > > does not have expressions that do case analysis (this is not lambda's
    > > fault, of course ;). The reason is that you really want to put each
    > > case on its own set of lines. This enhances readability at the expense
    > > of terseness. Since Python's statements are terminated by a newline, it
    > > would be rather awkward to have a kind of expression where good style
    > > calls for it to be spread out accross multiple lines.
    > >
    > > You can try to simulate these kinds expressions using into a list or
    > > dictionary, but this becomes rather messy. I think the only way to get
    > > this done properly is to use eval. For example:
    > >
    > > def recursiveFunction(args):
    > > ... # do stuff...
    > > choices = { True:"0", False:"recurisveFunction(newArgs)" }
    > > return eval( choices[predicate] )

    >
    > Why do you want to use eval here ?
    >
    > > The reason that you need eval is that you want to prevent any cases
    > > from being executed until you decide which one you want.

    >
    > What about:
    >
    > def recursiveFunction(args):
    > ... # do stuff...
    > ... # that defines 'newArgs' and 'predicate' of course ...
    > return (recursiveFunction, lambda x: 0)[predicate](newArgs)


    Sure, that works, but don't take things so literally. For instance, if
    you have a bunch of cases, you might not way to apply the same set of
    arguments to all of them.

    Also, let's not get distracted from the main point about how doing case
    analysis in an expression is ugly, making lambda's weaker in Python
    than in the language which inspired them.

    >
    > --
    > bruno desthuilliers
    > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
    > p in ''.split('@')])"
     
    danielx, Jul 20, 2006
    #16
  17. danielx wrote:
    > Bruno Desthuilliers wrote:
    >
    >>danielx wrote:
    >>(snip)
    >>
    >>
    >>>Python's lambda really can't be as powerful as Lisp's because Python
    >>>does not have expressions that do case analysis (this is not lambda's
    >>>fault, of course ;). The reason is that you really want to put each
    >>>case on its own set of lines.


    An expression can span several lines.

    > This enhances readability at the expense
    >>>of terseness. Since Python's statements are terminated by a newline,


    or by a ';'

    > it
    >>>would be rather awkward to have a kind of expression where good style
    >>>calls for it to be spread out accross multiple lines.


    I must be pretty dumb, but I don't see how this relate to the problem of
    case analysis in lambda expressions ?

    >>>You can try to simulate these kinds expressions using into a list or
    >>>dictionary, but this becomes rather messy. I think the only way to get
    >>>this done properly is to use eval. For example:
    >>>
    >>>def recursiveFunction(args):
    >>> ... # do stuff...
    >>> choices = { True:"0", False:"recurisveFunction(newArgs)" }
    >>> return eval( choices[predicate] )

    >>
    >>Why do you want to use eval here ?
    >>
    >>
    >>>The reason that you need eval is that you want to prevent any cases
    >>>from being executed until you decide which one you want.

    >>
    >>What about:
    >>
    >>def recursiveFunction(args):
    >> ... # do stuff...
    >> ... # that defines 'newArgs' and 'predicate' of course ...
    >> return (recursiveFunction, lambda x: 0)[predicate](newArgs)

    >
    >
    > Sure, that works, but don't take things so literally.


    Sorry for being pragmatic !-)

    > For instance, if
    > you have a bunch of cases, you might not way to apply the same set of
    > arguments to all of them.


    return {
    'case1' : lambda: someFunc(args1),
    'case2' : lambda: someFunc(args2),
    'case3' : lambda: someOtherFunc(args1, arg42),
    }.get(predicate, lambda: 0)()

    Still no need for eval()...

    Now of course there are limits to the exercice, and we're still far away
    from ML-like pattern matching or Lisp 'case' forms. As you noted, Python
    is a statement-based language, not an expression-based one like Lisp.
    This makes a definitive difference.

    > Also, let's not get distracted from the main point about how doing case
    > analysis in an expression is ugly,


    Ugliness is in the eyes of the beholder <wink>

    > making lambda's weaker in Python
    > than in the language which inspired them.


    The fact is that Python "lambdas" are *not* Lisp lambdas. Python
    "lambdas" are mostly a handy trick to turn a *simple* expression into a
    closure - and definitively not a basic building block of the language.

    Daniel, I of course do agree that Python lambdas are nothing near Lisp
    lambdas - FWIW, Python is not Lisp neither -, but that looks like an
    apple and banana comparison to me... IMHO, the most obvious problem with
    Python lambdas is the word "lambda" !-)


    --
    bruno desthuilliers
    python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
    p in ''.split('@')])"
     
    Bruno Desthuilliers, Jul 21, 2006
    #17
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Bill Johnson
    Replies:
    0
    Views:
    1,240
    Bill Johnson
    Jul 8, 2005
  2. Replies:
    3
    Views:
    488
    Ken Cox [Microsoft MVP]
    Oct 7, 2005
  3. Janet Collins
    Replies:
    0
    Views:
    1,157
    Janet Collins
    Jan 13, 2006
  4. Replies:
    1
    Views:
    851
    Juan T. Llibre
    Feb 8, 2006
  5. Alek Nazarian
    Replies:
    7
    Views:
    3,232
    Alek Nazarian
    Oct 22, 2003
Loading...

Share This Page