Objectives Of This Post
Continuing my Python Series (see my first post here and second one here), I went through how to use List, Set and Dictionary Comprehensions, in Python, to replace loops that generate collections of items. In this post, we will explore Lambdas.
What Are Lambdas?
A Lambda Function is a concise way to define a limited anonymous function in Python. Here is an example of an identity function as a standard python function, and then the same function expressed as a Lambda function.
def identity(x): return x
Note the identity function needs a name (identity)
Where the Lambda function has no name.
In the above example, we defined a Lambda function but gave it no name and provided it no arguments, so it actually has no use. To use the lambda, we need to provide it with argument(s).
Here we provide the lambda function with an argument and it returns the value
Obviously, we could ask a Lambda function to do more than just return the argument you pass to it:
from math import pi (lambda x:x*pi)(10)
Here we imported pi from the math package and used it in our Lambda function to return the input times pi.
We can assign a lambda function to a variable, for that matter we could assign any function to a variable when we do that the variable acts as a pointer to the function that we can call like any other function.
from math import pi timesPi = (lambda x:x*pi) timesPi(10)
In this example, we assign the Lambda function to a variable called timesPi. We can then call that function by referring to the timesPi variable and passing an argument.
Lambda functions aren’t limited to a single argument. You can provide multiple arguments using a comma.
fullNameUpper = (lambda first, last: first.upper() + ' ' + last.upper()) fullNameUpper('Code', 'Wrench')
Here we supply a first and last name and the function returns the uppercased concatenation of the names.
All of the previous examples of Lambda functions were rather trivial. An example of where a Lambda function might come in handy is a situation where you have a list of strings that you need to sort, using the sorted function in Python. But you want to sort the values based on just the numeric portion of the string.
IDs = ['A987', 'C443', 'B234', 'D123'] print(sorted(IDs))
['A987', 'B234', 'C443', 'D123']
Note that the list is sorted alphabetically. So even those 987 comes after 234 it appears first in the list.
IDs = ['A987', 'C443', 'B234', 'D123'] print(sorted(IDs, key=(lambda id: int(id[1:]))))
['D123', 'B234', 'C443', 'A987']
The sort function will take a key argument. This argument specifies a value to use to do the sort. In this case, we provided a lambda which will take each ID in the IDs list and remove the first character and turn the remaining value into an integer and used that to sort the list again. Note we have the list sorted in numerical order regardless of the leading character.
Lambdas are interesting and can be a bit hard to wrap your head around. At least they were for me at first. But they add a bit of convenience when you need to do a transformation inline on a list or interact with each element of a collection before processing it. They shouldn’t be overused, and the examples of naming them and calling them like typical Python functions is a bad practice in most cases. But in the right spot, they are very handy.
Stay tuned for more Python mini tutorials.