Sometimes we need a callable object that we can use as an argument to a function. While we could create a function for that purpose, there is another way that needs less typing.
This post is part of my journey to learn Python. You can find the other parts of this series here.
What is a lambda function?
Lambda functions, also known as anonymous functions, are functions without a name and only one statement. What sounds strange is indeed a great help when you combine it with built-in functions like filter() or map(). You not only save yourself a lot of typing, your code is simpler to understand when you have everything that goes on in front of you.
The syntax for a lambda function looks like this:
lambda arguments: expression
The lambda at the beginning is the keyword you must write; the arguments are the variables you want to use inside your expression. The arguments are optional, if you do not need them you write the : directly after lambda (lambda: expression). For lambdas you do not write return statements, that is done behind the scenes.
You can write a lambda function that checks if a number is even like this:
1 |
lambda x: x % 2 == 0 |
That will return True if the value we give in is even and False otherwise.
If we want to run our lambda in the REPL we may give it a name:
1 2 3 4 5 6 7 |
>>> e = lambda x: x % 2 == 0 >>> e(5) False >>> e(4) True >>> e <function <lambda> at 0x01129D60> |
If you prefer a function instead, you could write it this way:
1 2 3 4 5 6 7 8 9 |
>>> def even(x): ... return x % 2 == 0 >>> even(5) False >>> even(4) True >>> even <function even at 0x010577C0> |
Where lambdas are a great help
We can combine lambdas with a wide range of other functions. If we want to filter a list, we can use our lambda from above like this:
1 2 3 4 |
>>> digits = [1,2,3,4,5,6,7,8,9,10] >>> new_list = list(filter(lambda x: x%2 == 0, digits)) >>> new_list [2, 4, 6, 8, 10] |
Or we can use the map() function to modify values of a list without much effort:
1 2 |
>>> list(map(lambda x: x.upper(), ['cat', 'dog', 'cow'])) ['CAT', 'DOG', 'COW'] |
In both examples we could use a function. However, the lambda is all we need and the readability of the code does not suffer.
Conclusion
Lambdas cannot substitute functions, but they are a great help when you just need a single expression as a parameter to another function.