[Tutor] Lambda?? Whaaaaat?

Steven D'Aprano steve at pearwood.info
Fri Aug 31 06:43:08 CEST 2012


On 31/08/12 13:39, Scurvy Scott wrote:

> I'm fairly new to python having recently completed LPTHW. While
>randomly reading stack overflow I've run into "lambda" but
>haven't seen an explanation of what that is, how it works, etc.
> Would anyone care to point me in the right direction?

Lambda is just a short-cut for making a function. Instead of writing
a function like this:

def func(a, b=2):
     return a*b - 1


you can do this instead:

lambda a, b=2: a*b - 1


Note that you don't use the "return" keyword in lambdas.

There are two limitations on functions you create with lambda:

* they don't have names -- they are "anonymous functions"
   (this is both a strength and a weakness)

* you are limited to a single expression in the function body,
   so big complicated functions can't be (easily, or at all) be
   created with lambda

Other than that, they are ordinary functions no different from
those you create using def.

Why would you use lambda instead of def? Frankly, normally you
wouldn't, but there are a few situations where you might. One
of the most common is using "callback functions" for GUI
frameworks or similar.

Here's another example, easier to show. Suppose you want to
sort a list of movie titles, but skipping leading "The".

movies = ["Star Wars", "The Lord of the Rings", "Zoolander",
     "The Last Supper", "True Lies", "Watchmen", "Con Air",
     "The Frighteners", "The Long Kiss Goodnight", "The Avengers"]

from pprint import pprint
movies.sort(key=lambda title: title.replace("The ", ""))
pprint(movies)


Without lambda, you would have to do this:

def key_function(title):
     # I can't think of a better name
     return title.replace("The ", "")

movies.sort(key=key_function)


which is a bit of a waste if you only use key_function once and
never again, or if you have many different key functions.

(Note that, strictly speaking, my key function above is not quite
right. Here is a better one:

lambda title: title[4:] if title.startswith("The ") else title

but that's a bit harder to understand.

So the strength of lambda is that it is an expression, not a
statement, and can be embedded directly where you want it.
Here's a list of functions:


list_of_functions = [
     lambda s: s.upper() + "!!",
     lambda s: "??" + s.lower(),
     lambda s: "?" + s.title() + "!",
     ]

for func in list_of_functions:
     print(func("Hello world"))



Where does the name come from? Lambda is the Greek letter L,
and for reasons I don't know, it is the traditional name used
for functions in some of the more abstract areas of computer
science. From computer science the name became well known in
programming languages like Lisp, and from there to Python.



-- 
Steven


More information about the Tutor mailing list