The ABCs of Python: The Silence of the “lambda”

Just for minute or so, forget what Python keyword “lambda” can do for you. Savor the sound of the word itself. The accent is on the first syllable. It has a sophisticated, round and educated sound to it.

It’s also a cool-looking word in English, partly because it’s redolent of various animals: lamb, lama, panda. You can just about envision its surreal advent through a shadowy forest.

The word also feels ancient, and so it is, being the 11th letter of the Greek alphabet. Some version of the lambda sound probably rolled off Homer’s tongue as he chanted his epic poems.  We can imagine Sophocles using it to write his tragedies, Herodotus his histories, Aristophanes his comedies, and Aristotle his philosophies.

Since the time of those famous ancients, this one letter name has taken on many other meanings. There is lambda as a type of calculus, and lambda the junction in the brain, lambda the uncharged and unstable elementary particle, and lambda the phage.

And then there’s lambda the Python keyword, the one that can be used to create small, anonymous functions and procedures that are often concocted on the fly, nearly as obscure, silent and subtle as the elementary particle or the bacterial virus.

Lambda is something Python beginners should learn, if only to be able to comprehend the more Pythonic lines of code written by the more practiced wielders of the form. There have been times when I’ve written programs of 20 lines or more, only to discover that the same purpose could be achieved in one or two written with the lambda. It’s simultaneously breath-taking and maddening. (I should note, though, that lambda isn’t magic. You can write very succinct code when using standard forms of functions, as well. But lambda can help condense and add flair.)

Here’s an example of a simple function with the familiar def:

def cubism (root):
    return root**3
print(cubism(10))

Now here’s an example of lambda equivalent:

y = lambda x: x**3
print (y(10))

They do the same thing and get the same result (that is, 1000). We could even use the same terms, if we like. The lambda version is, however, a little less easy to read for the beginner unfamiliar with its syntax. That is due, in part, to the fact that lambda doesn’t need a return. Python automatically returns whatever expression is provided: in this case, x**3.

(By the way, an “expression” is code that returns some sort of value, as Python Conquers The Universe makes clear.  Lambda is more limited than a normal function in that it can only take one expression.)

Lambda often goes hand in hand with tools such as filter(), map() and sort(). Let’s use sort() on a list of the dwarves from The Hobbit to give you an idea of how it works. Here, we are using lambda to create three different functions on the fly that give us the list sorted by three different criteria:

We tell sorted to sort the tuples by a specific “key,” and that key is a lambda function. For example, in the first one, “lambda height” tells Python, “We are defining a quick function called ‘height’.” The next part, which is “height[1]”, works on the second item in each tuple in the list, all of which are indicators of the height of the dwarves.

Image by Rotox: Wikipedia
dwarves = [
('Fili', 126, 'blue'),
('Kili', 125, 'blue'),
('Oin', 134, 'brown'),
('Gloin', 136, 'brown'),
('Dwalin', 132, 'green'),
('Balin', 139, 'red'),
('Bifur', 137, 'yellow'),
('Bofur', 135, 'yellow'),
('Bombur', 140, 'green'),
('Dori', 141, 'purple'),
('Nori', 138, 'purple'),
('Ori', 133, 'grey'),
('Thorin Oakenshield', 145, 'blue')
]

print("A list of the Thorin's company sorted by height in cm: " 
+ str(sorted(dwarves, key=lambda height: height[1])))

print('')

print("A list of the Thorin's company sorted by name: " 
+ str(sorted(dwarves, key=lambda name: name[0])))

print('')

print("A list of the Thorin's company sorted by color of hood: " + str(sorted(dwarves, key=lambda hood: hood[2])))

We get the following:

A list of the Thorin’s company sorted by height in cm: [(‘Kili’, 125, ‘blue’), (‘Fili’, 126, ‘blue’), (‘Dwalin’, 132, ‘green’), (‘Ori’, 133, ‘grey’), (‘Oin’, 134, ‘brown’), (‘Bofur’, 135, ‘yellow’), (‘Gloin’, 136, ‘brown’), (‘Bifur’, 137, ‘yellow’), (‘Nori’, 138, ‘purple’), (‘Balin’, 139, ‘red’), (‘Bombur’, 140, ‘green’), (‘Dori’, 141, ‘purple’), (‘Thorin Oakenshield’, 145, ‘blue’)]

A list of the Thorin’s company sorted by name: [(‘Balin’, 139, ‘red’), (‘Bifur’, 137, ‘yellow’), (‘Bofur’, 135, ‘yellow’), (‘Bombur’, 140, ‘green’), (‘Dori’, 141, ‘purple’), (‘Dwalin’, 132, ‘green’), (‘Fili’, 126, ‘blue’), (‘Gloin’, 136, ‘brown’), (‘Kili’, 125, ‘blue’), (‘Nori’, 138, ‘purple’), (‘Oin’, 134, ‘brown’), (‘Ori’, 133, ‘grey’), (‘Thorin Oakenshield’, 145, ‘blue’)]

A list of the Thorin’s company sorted by color of hood: [(‘Fili’, 126, ‘blue’), (‘Kili’, 125, ‘blue’), (‘Thorin Oakenshield’, 145, ‘blue’), (‘Oin’, 134, ‘brown’), (‘Gloin’, 136, ‘brown’), (‘Dwalin’, 132, ‘green’), (‘Bombur’, 140, ‘green’), (‘Ori’, 133, ‘grey’), (‘Dori’, 141, ‘purple’), (‘Nori’, 138, ‘purple’), (‘Balin’, 139, ‘red’), (‘Bifur’, 137, ‘yellow’), (‘Bofur’, 135, ‘yellow’)]

Okay, there’s more to be said on the subject of lambda, but this gives you at least glimpse of the strange beast. For more on lambda, I recommend the following:

Yet Another Lambda Tutorial

Bogotobogo

Official Python Documentation on Lambda Expressions