In this article, I will teach you exactly what a python lambda is.
As a matter of fact if you know what functions are and how to define functions in Python then you already know what a lambda is.
A Python lambda is just a Python function.
But may be like a special type of function that have limited capabilities 🙂
If you want to dive deeper and learn more about lambdas and how they are used in Python then this is what this article is about.
Here is what I will be talking about in this article.
- What is Python lambda?
- Lambdas with multiple arguments
- Lambdas with no arguments
- Multiline lambdas
- Examples of lambda in action
- Expressions vs Statements
What is Python lambda?
Before trying to understand what a Python lambda is, let’s first try to understand what a Python function is at a much deeper level.
This will require a little bit of a paradigm shift of how you think about functions.
As you already know, everything in Python is an object.
For example, when we run this simple line of code.
x = 5
What actually happens is we’re creating a Python object of type int that stores the value 5.
x is essentially a symbol that is referring to that object.
Now let’s check the type of x and the address it is referring to.
We can easily do that using the type and the id built-in functions.
>>> type(x) <class 'int'> >>> id(x) 4308964832
As you can see, x refers to an object of type int and this object lives in the address returned by the id
Pretty straightforward stuff.
Now what happens when we define a function like this one:
>>> def f(x): ... return x * x ...
Let’s repeat the same exercise from above and inspect the type of f and its id.
>>> def f(x): ... return x * x ... >>> type(f) <class 'function'> >>> id(f) 4316798080
hmm, very interesting.
So it turns out there is a function class in Python and the function f that we just defined is an instance of that class.
Exactly like how x was an instance of the integer class.
In other words, you can literally think about functions the same way you think about variables.
The only difference is that a variable stores data whereas a function stores code.
That also means you can pass functions as arguments to other functions, or even have a function be the return value of another function.
let’s look at a simple example where you can pass the above function f to another function.
def f(x): return x * x def modify_list(L, fn): for idx, v in enumerate(L): L[idx] = fn(v) L = [1, 3, 2] modify_list(L, f) print(L) #output: [1, 9, 4]
Give yourself a minute and try to understand what this code does before you read on…
As you can see, modify_list is a function that takes a list L and a function fn as arguments.
It then iterates over the list item-by-item and applies the function fn on each.
This is a very generic way of modifying the items of a list as it allows you to pass in the function that is responsible for the modification which can be very useful as you will see later.
So for example when we pass the function f to modify_list, the result will be that each item in the list will be squared.
We could pass any other custom function that can modify the list in any arbitrary way.
That’s pretty powerful stuff right there!
Alright now that I have laid down some foundations, let’s talk about lambdas.
A Python lambda is just another method to define a function.
The general syntax of a Python lambda is:
lambda arguments: expression
Lambda functions can accept zero or more arguments but only one expression.
The return value of the lambda function is the value that this expression is evaluated to.
For example, if we want to define the same function f that we defined before using lambda syntax, this is how it will look like:
>>> f = lambda x: x * x >>> type(f) <class 'function'>
But you might be asking yourself why the need for lambdas in the first place when we can just define functions the traditional way?
Actually, lambdas are only useful when you want to define a one-off function.
In other words, a function that will be used only once in your program. These functions are called anonymous functions.
As you will see later, there are many situations where anonymous functions can be useful.
Lambdas with multiple arguments
As you saw earlier, it was easy to define a lambda function with one argument.
>>> f = lambda x: x * x >>> f(5) 25
But if you want to define a lambda function that accepts more than one argument, you can separate the input arguments by commas.
For example, say we want to define a lambda that takes two integer arguments and returns their product.
>>> f = lambda x, y: x * y >>> f(5, 2) 10
How about if you want to have a lambda that accepts no arguments whatsoever?
Lambdas with no arguments
Say you want to define a lambda function that takes no arguments and returns True.
You can achieve this with the following code.
>>> f = lambda: True >>> f() True
Yes, at some point in your life you will be wondering if you can have a lambda function with multiple lines.
And the answer is:
No you can’t 🙂
Python lambda functions accept only one and only one expression.
If your function has multiple expressions/statements, you are better off defining a function the traditional way instead of using lambdas.
Examples of Lambda in action
Now let’s discuss some of the most common places where python lambdas are heavily used.
Using lambdas with map
One common operation you will apply to Python lists is to apply an operation to each item.
Map is a Python built-in function that takes in a function and a sequence as arguments and then calls the input function on each item of the sequence.
For example, assume we have a list of integers and we want to square each element of the list using the map function.
>>> L = [1, 2, 3, 4] >>> list(map(lambda x: x**2, L)) [1, 4, 9, 16]
Note that in Python3, the map function returns a Map object whereas in Python2 it returns a list.
See, instead of defining a function and then passing it to map as an argument, you can just use lambdas to quickly define a function inside the map parentheses.
This makes sense especially if you are not going to use this function again in your code.
Let’s take a look at another case where lambdas can be useful.
Using lambdas with filter
As the name suggests, filter is another built-in function that actually filters a sequence or any iterable object.
In other words, given any iterable object (like a list), the filter function filters out some of the elements while keeping some based on some criteria.
This criteria is defined by the caller of filter by passing in a function as an argument.
This function is applied to each element of the iterable.
If the return value is True, the element is kept. Otherwise, the element is disregarded.
for example, let’s define a very simple function that returns True for even numbers and False for odd numbers:
def even_fn(x): if x % 2 == 0: return True return False print(list(filter(even_fn, [1, 3, 2, 5, 20, 21]))) #output: [2, 20]
That said, With the magic of lambdas you can do the same thing more succinctly.
The above code will transform into this one-liner
print(list(filter(lambda x: x % 2 == 0, [1, 3, 2, 5, 20, 21])))
And that, my friend, is the power of lambdas.
Using lambdas with list sorting
Sorting a Python list is a very common operation.
In fact I have a whole in-depth article dedicated to this topic.
If you have a list of numbers or strings, then sorting a list is very straightforward.
You can just use the sort or sorted built-in functions.
However, sometimes you have a list of custom objects and may be you want to sort the list based on a specific object field.
In this case, you can pass an optional key parameter to either sort or sorted.
This key parameter is actually of type function.
The function is applied to all the list items and the return value is what’s going to be sorted.
Let’s take an example.
Assume you have an Employee class that looks like this
class Employee: def __init__(self, name, age): self.name = name self.age = age
Now Let’s create some Employee objects and append them to a list.
Alex = Employee('Alex', 20) Amanda = Employee('Amanda', 30) David = Employee('David', 15) L = [Alex, Amanda, David]
Now say we want to sort this list based on the age of the employees, here is what we should do:
L.sort(key=lambda x: x.age) print([item.name for item in L]) # output: ['David', 'Alex', 'Amanda']
See how we used a lambda expression as the key parameter instead of having to define a function externally and then passing this function to sort.
One word on Expressions vs Statements
Like I mentioned earlier, lambdas can use only one expression as the body of the lambda function.
Notice I didn’t say one statement.
Statements and expressions are two different things but they can be confusing so let me try to clarify the differences.
In programming languages, a statement is a line of code that does something but it doesn’t evaluate to a value.
For example, an if statement, a for loop, a while loop, all of these are examples of statements.
You can’t simply replace the statement with a value because statements don’t evaluate to a value.
Expressions on the other hand are evaluated to a value.
You can easily replace all the expressions in your programs with some values and your program will work correctly.
3 + 5 is an expression that is evaluation to 8
10 > 5 is an expression that is evaluated to True
True and (5 < 3) is an expression that is evaluated to False
Lambda’s body has to be an expression because the value of this expression is the return value of the function.
Make sure you remember this point when you are writing your next lambda function 🙂
Check out the Courses section!
Are you Beginning your Programming Career?
I provide my best content for beginners in the newsletter.
- Python tips for beginners, intermediate, and advanced levels.
- CS Career tips and advice.
- Special discounts on my premium courses when they launch.
And so much more…