[Tutor] Demystification of Lambda Functions

Alan Gauld alan.gauld at btinternet.com
Wed Oct 28 06:23:56 EDT 2015


On 28/10/15 01:04, Hunter Jozwiak wrote:

> I am not sure exactly why there would be a practical use for a lambda
> function, other than the fact that you can make one-liner functions that
> take parameters in to a variable. Or at least that is how things look when
> they are written. Can I have some demystification?

One thing to remember when dealing with Python is that it started out as 
a teaching language. That is, a language used to teach computer science 
and programming. As such, many of its features are designed
to be easy to use. Others are there to demonstrate computer science 
concepts.

One of those concepts is the idea of functional programming, where 
functions are treated like data objects. Many of those ideas in turn 
come from Church's "Lambda Calculus" and the idea of a lambda being an 
executable object. In other languages lambdas are much more powerful but 
in Python they were limited to a single expression so their full
power is harder to see.

If you look at JavaScript (or Lisp) it uses the concepts behind Lambda
much more and the use of anonymous functions is almost endemic in
modern Javascript libraries like JQuery, Angular, Node and so on.
In Python we are forced to define complex functions as separate 
entities, so the JScript style cannot be used.

So what are we left with in Python?

1) lambda makes programmers aware of the term 'lambda' and that
it is somehow significant in computer science. (Just like with
you, it stimulates curiosity).

2) lambdas are useful for teaching that

def f(x): return expression(x)

is the same as writing

f = lambda x: expression(x)

where f is just a variable name like any other.
(Whereas the def syntax tends to suggest that the f name is
somehow different to other names, that it has some kind of
superpowers just because its a function name, when in fact
it doesn't. Its just a name.)

3) lambdas allow us to create short anonymous functions in call
backs or to wrap longer generic functions with specific values.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list