Brace yourself, in this tutorial, we’ll uncover the ins and outs of lambda function usage in Python with this in-depth tutorial.
You’ll be able to learn when to harness their power and when to avoid them. However, you can read our comprehensive tutorial on Python lambda covering this topic in detail. Don’t miss to read it if you are first time using the lambda function.
Let’s explore the world of compact functions and discover their limitless possibilities!
Understanding the Lambda Function Usage
Let’s first quickly understand what is lambda in Python.
What is lambda in Python?
Python provides the ability to create concise anonymous functions, referred to as lambda functions, using the “lambda” keyword. These functions lack a name and are defined in a single line. Our comprehensive explanation of Python lambda functions will allow for a thorough understanding of their functionality.
Lambda functions are structured similarly to traditional functions, executing a block of code and returning a value. As an illustration, consider the following example defining a lambda function that multiplies two numbers.
>>> mul = lambda a, b: a * b >>> mul(2, 8) 16
Moreover, the same function, we can create using the def keyword. See the code below:
>>> def mul(a, b): ... return a * b >>> mul(2, 8) 16
Also Read: Higher Order Functions in Python
What advantage does lambda offer? Why do you need it?
Firstly, you should note that you don’t have to use lambda at all. There is nothing that forces you to do it. You can code any logic without using it. However, it brings ease while coding in specific scenarios. For example – When you need a function that is short and straightforward. Also, you need to call it once in a program’s life.
Usually, a programmer writes functions with two objectives in mind:
- To eliminate redundant code
- To improve modularity
Assume, you have a project which has a lot of unnecessary code in several of its modules. You can create a single definition, assign some proper name, include it, and use it in all places.
On the other hand, there is one piece of code that does a pre-defined task. But it is a short and complicated code that hampers the overall readability. Hence, it is deemed reasonable to wrap this block in a function.
Here, the question comes that the function would get called once, so why give it a name? It should be “anonymous” instead. And we can have it defined inline where it is required. That’s the situation where lambda is useful.
Lambda can provide a quick shortcut to a function. Check the below Python example for writing lambdas to sort a list using some key.
>>> sorted(range(-3, 9), key=lambda x: x ** 3) [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
A lambda function also supports lexical closures, which means that it can retain values from its lexical neighbors while going out of scope. See the Python code below.
def makeAdder(new): return lambda summation: summation + new add_3 = makeAdder(3) add_4 = makeAdder(4) print(add_3(6)) print(add_4(6))
After the execution, the output is as follows:
9 10
In the above sample code, the (summation + new) lambda retains the value of “new” from the makeAdder() function.
Lambda function usage
There are many situations where a lambda function is the shortest way to implement the logic.
When you want to return a function from some other function, it is better to use lambda. Check out the lambda usage in Python code shown below.
>>> def summation(new): ... return lambda x: x + new ... >>> proc = summation(7) >>> proc(3) 10
The above approach works as the basis of making function wrappers, for example – Python decorator.
Lambda is useful for concatenating the elements of a list using reduce() method. Check how the below Python code is using it.
>>> from functools import reduce >>> reduce(lambda x, y: '{}, {}'.format(x, y), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) '0, 1, 2, 3, 4, 5, 6, 7, 8, 9'
Another usage (sorting by alternate key) which we explained above.
>>> sorted([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda m: abs(7-m)) [7, 6, 8, 5, 9, 4, 3, 2, 1, 0]
You can use the lambda function in your routine programming tasks. However, it may make you take some time to get used to, but after understanding, you should be able to use it with ease.
When to not use a lambda function?
- You won’t use something that doesn’t return a value with lambda. If it isn’t an expression, then you shouldn’t place it inside a lambda.
- Don’t put assignment statements into lambda as they don’t return anything.
When should you be using it?
- Expressions using maths operators, strings, and list comprehensions are all good candidates to use with lambda.
- Making a function call is okay. For example – print() is a function in Python, hence, is allowed in lambda.
- Lambda also accepts functions that return None along with conditional expressions.
And certainly, you won’t want to miss the below tutorials: