Welcome to Tony's Notebook

Introducing Python lambda

I seem to have managed to avoid Python lambda for years. I'd never really needed it until I ran into a problem recently - I'll get to that in a moment.

So what is this mysterious lambda?

In a nutshell lambda is how to implement an anonymous function in Python. You probably use anonymous functions all the time if you are familiar with Node - mostly the callbacks are implemented as anonymous functions and you get that (p1, p2) => { ... } thing going on. A lot. In this case p1 and p2 are the parameters, and the body of the function is contained within { ... }, but the function doesn't have a name.

With some limitations you can do something similar in Python.

lambda a : a + 1 

This declares an anonymous function that adds 1 to the input. There can be any number of input parameters, but they can only be mapped to one expression:

lambda a, b : a + b

Looking at these examples you might be wondering - what's the point? Well, that's what I thought too for a long time. But it turns out there are specific cases where lambda turns out to be very useful, and that brings me back to my problem...

So, I had an array of objects that I needed to sort. Putting that in Python terms I had a list of dictionaries that I needed to sort. Simplifying, this looked like:

files = [ {"filename": "file1.txt", "date": "2019-10-20"}, {"filename": "file2.txt", "date": "2019-08-09"}, ... ]

Now, I want to sort this list based on the date in each object. Awkward right?

Well, you can try and use sorted() to sort the list. Here's prototype:

sorted(iterable, key, reverse)

Key and reverse are optional but very useful.

Now, iterable will typically be a list. reverse is a boolean and is False by default, giving you ascending order.

The fly in the ointment - key is actually a function. It can be a key (on which basis to sort), or the basis of a comparison, but it always has to be specified as a function. In our case we only want to sort based on a key value, but how do we do that as a function? You guessed it, lambda to the rescue!

Here's the code:

files = sorted(files, key=lambda x: x['date'], reverse=True)

So key is set to the anonymous function x: x['date'], which takes in a list object and returns the date field, and that is used by sorted() to sort.

I also set reverse to True as I want the newest files to be first.

So, lambda is another of those things that seems obscure, until you actually need it, and then it's a total hero.