Lambda Functions in Python:

What Are They Good For?


An introduction to “lambda” expressions in Python: What they’re good for, when you should use them, and when it’s best to avoid them.

The lambda keyword in Python provides a shortcut for declaring small anonymous functions. Lambda functions behave just like regular functions declared with the def keyword. They can be used whenever function objects are required.

For example, this is how you’d define a simple lambda function carrying out an addition:

                             
>>> add = lambda x, y: x + y 
>>> add(5, 3)                
8                             
 
You could declare the same add function with the def keyword:


>>> def add(x, y):
...     return x + y
>>> add(5, 3)
8

 
Now you might be wondering: Why the big fuss about lambdas? If they’re just a slightly more terse version of declaring functions with def, what’s the big deal? Take a look at the following example and keep the words function expression in your head while you do that:

>>> (lambda x, y: x + y)(5, 3)
8 
 
 
Okay, what happened here? I just used lambda to define an “add” function inline and then immediately called it with the arguments 5 and 3.

Lambdas You Can Use

When should you use lambda functions in your code? Technically, any time you’re expected to supply a function object you can use a lambda expression. And because a lambda expression can be anonymous, you don’t even need to assign it to a name.
 This can provide a handy and “unbureaucratic” shortcut to defining a function in Python. My most frequent use case for lambdas is writing short and concise key funcs for sorting iterables by an alternate key:

>>> sorted(range(-5, 6), key=lambda x: x ** 2)
[0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5]
 
Like regular nested functions, lambdas also work as lexical closures.

What’s a lexical closure? Just a fancy name for a function that remembers the values from the enclosing lexical scope even when the program flow is no longer in that scope. Here’s a (fairly academic) example to illustrate the idea:

>>> def make_adder(n):
...     return lambda x: x + n

>>> plus_3 = make_adder(3)
>>> plus_5 = make_adder(5)

>>> plus_3(4)
7
>>> plus_5(4)
9
 
In the above example the x + n lambda can still access the value of n even though it was defined in the make_adder function (the enclosing scope).
 
Sometimes, using a lambda function instead of a nested function declared with def
can express one’s intent more clearly. But to be honest this isn’t a 
common occurrence—at least in the kind of code that I like to write.
 

Comments

Popular posts from this blog