Lambda at Work

Lambda Finally, several years after learning lambda expressions, I got a chance to use one at work a few days ago. As long as I’m putting a notch in my nerd belt, I’d like to write about what lambda is and how it can be useful.

A lambda expression defines an anonymous function. Here’s a regular function definition:

` def inc(x): return x + 1 `{lang=”python”}

This definition binds the name inc in the local namespace to a function object. To get the exact same functionality using lambda, assign the lambda expression to a variable:

` inc = lambda x: x + 1 `{lang=”python”}

A lambda has two parts: the argument list (only one arg in this case) before the and an expression after. It can’t contain statements (like assignments or print) because it’s an expression itself. This is a pretty useless example, so let me show how I used it today.

When you call list.sort(), Python sorts it by calling the built-in cmp() function on pairs of elements from the list, which is defined as:

` def cmp(x, y): if (x < y): return -1 elif (x > y): return 1 else return 0 `{lang=”python”}

My problem was that I was sorting a list of lists, a couple rows of statistics for a spreadsheet. Python was sorting it by the columns in order from left to right, and I needed to sort by one of the middle columns. Luckily, you can pass a new cmp function object to sort().

` list.sort(lambda x,y: cmp(x[2], y[2])) `{lang=”python”}

The lambda defines a function that takes arguments x, y and calls the built-in cmp function with item two of the inner list. The sort happens an inside column of the list rather than the first.

I could have defined a function, but that would be overkill for code I’d only call from one place. This simpler and more readable. It’s not a big win, but every little bit helps.

As a side note, Python 2.4 added a key argument to sort() that simplifies my code. If it’s set, Python calls it with the list element and passes what it returns into cmp. I figured the cmp example would show off lambda better, but in case you’re curious:

` list.sort(key=lambda x:x[1]) `{lang=”python”}

It’s been tough to write this and not start pulling in concepts from functional programming. Maybe I’ll get to use them next week. In the meantime, I’d like to hear more real-world uses of lambda if you’ve got one to share.