- 1. Lambda Expression Python
- 2. Introduction to Python3 Lambda Expressions
- 3. Declaring Lambda Expressions in Python
- 4. What Exactly is an Expression?
- 5. Python – When to Use Which Lambda Expression
- 6. Defaults in Python Lambda Expressions
- 7. Syntax of Python Lambda Expressions
- 8. Python Lambdas with In-Built Functions
- 9. Conclusion
1. Lambda Expression Python
In this Python Tutorial we will study, What is Lambda Expression Python, Declaring Lambda Expressions in Python, What is an Expression, When to use Python expression, Default in Python3 Lambda expression, Syntax of Python Lambda Expressions, Python Lambda with inbuilt Python lambda functions, and some python functions are: reduce(), map(), and filter(). When creating functions in Python, we use the def keyword. We bind them to a name while doing so. But sometimes, we may want to declare a function anonymously. Or we may want to use a function only once. In such a case, defining a function seems a bit extra.
2. Introduction to Python3 Lambda Expressions
lambda expression Python allow us to define a function anonymously. It is worthwhile to note that it is an expression, not a statement. That is, it returns a value; it has an implicit return statement. The following is the Python syntax of a lambda expression in Python.
Where you place lambda expression Python, it returns the value of the expression.
3. Declaring Lambda Expressions in Python
To declare a lambda, you use the lambda keyword.
>>> lambda e:e-2 <function <lambda> at 0x03DBA978>
You can assign it to a variable if you want to be able to call it again later.
>>> downbytwo=lambda e:e-2
Here, e is the argument, and e-2 is the expression. Then you would call it like you would call any other Python Lambda function. Here, we passed the integer 1 as an argument.
You can also pass an argument along with the declaration. Use parentheses for this.
>>> (lambda e:e-2)(1)
4. What Exactly is an Expression?
As we’ve seen, the expression is what the Python3 lambda returns, so we must be curious about what qualifies as an expression. An expression here is what you would put in the return statement of a Python Lambda function. The following items qualify as expressions.
- Arithmetic operations like a+b and a**b
- Function calls like sum(a,b)
- A print statement like print(“Hello”)
Other things like an assignment statement cannot be provided as an expression to Python lambda because it does not return anything, not even None.
5. Python – When to Use Which Lambda Expression
Like we’ve seen so far, Python lambda expressions may take arguments, and takes one expression. The value of this expression is what it returns after evaluating. Lambda expression Python isn’t necessary, but it’s handy in certain situations. These are:
1. When you have only a single statement to execute in your Python Lambda function
Suppose we want to print a Hello in the body of a function printhello(). In this function’s body, we have only one line of code.
>>> def printhello(): print("Hello") >>> printhello()
Now, let’s do this with a lambda expression Python.
>>> (lambda :print("Hello"))()<strong>
Notice that we did not provide any arguments here. We’ll discuss this in a later section in this article. Let’s take another example yet.
>>> z=lambda a=2:print("Hello") >>> z()
2. When you need to call that code only once
One of the main reasons why we use functions, apart from modularity, is reusability of code. But when you want to need some code only once, or less often, you may use a lambda expression in place of defining a function for it.
6. Defaults in Python Lambda Expressions
In Python, and in other languages like C++, we can specify default arguments. But what is that? Suppose a function func1() has an arity of 2 with parameters a and b. What happens if the user provides only one argument or none? This is why you may want to provide default values for your parameters. Let’s take an example.
>>> def func1(a=2,b=3): print(a,' ',b) >>> func1()
Here, the default values for a and b are 2 and 3, respectively.
To call as y(), need default arguments:
>>> o=lambda x=1,y=2,z=3:x+y+z >>> o(2,3)
>>> o <function <lambda> at 0x00A46150> >>> o()
7. Syntax of Python Lambda Expressions
We’ve seen how we declare lambda expressions in Python, but where there are building blocks, there are possibilities. So, let’s see what we can or can’t do with a lambda.
a. Python Arguments
One or more variables appearing in the expression may be declared previously. But if it’s there in the arguments, either it should have a default value or must be passed as an argument to the call.
>>> a,b=1,2 >>> y=lambda a,b:a+b >>> y() Traceback (most recent call last): File "<pyshell#167>", line 1, in <module> y()
TypeError: <lambda>() missing 2 required positional arguments: ‘a’ and ‘b’
Here, both a and b are missing values.
>>> y=lambda a:a+b >>> y() Traceback (most recent call last): File "<pyshell#169>", line 1, in <module> y()
TypeError: <lambda>() missing 1 required positional argument: ‘a’
The variable a is still missing a value.
>>> y=lambda :a+b >>> y()
Finally, since no argument here is missing a value, it works just fine.
b. Omitting Arguments
It isn’t mandatory to provide arguments to a lambda expression in Python, it works fine without them.
>>> y=lambda :2+3 >>> y()
Another example would be where the expression is a print statement.
>>> (lambda :print("Hi"))()
Hence, we conclude that omitting arguments is acceptable.
c. Omitting the Expression
Now let’s try if it works without an expression.
>>> y=lambda a,b:
SyntaxError: invalid syntax
Clearly, it didn’t work. And why would it? The expression’s value is what it returns, so without an expression, it would be a waste of time.
8. Python Lambdas with In-Built Functions
There are some built-in functions, like filter() and map(), on which we can apply Python lambda expressions to filter out elements from a list. Let’s see how. First, we take a list called numbers.
Next, we take a lambda function as follows.
The filter() function takes two parameters- a function, and a list to operate on. Finally, we apply the list() function on this to return a list.
>>> list(filter(lambda x:x%3==0,numbers))
[0, 3, 6, 9]
This is the final code for our purpose, and guess what it does. Well, this code takes the list ‘numbers’, and filters out all elements from it except those which do not successfully divide by 3.
Note that this does not alter the original list.
The map() function, unlike the filter() function, returns values of the expression for each element in the list. Let’s take the same list ‘numbers’.
>>> list(map(lambda x:x%3==0,numbers))
[True, False, False, True, False, False, True, False, False, True, False]
Lastly, the reduce() function takes two parameters- a function, and a list. It performs computation on sequential pairs in the list and returns one output. But to use it, you must import it from the functools module.
>>> from functools import reduce >>> reduce(lambda x,y:y-x,numbers)
Let’s perform a dry run.
Hence, it outputs 5. Let’s take another example.
>>> reduce(lambda x,y:y+x,numbers)
Try doing the same thing here for y+x instead; you should get 55.
This was all for the lambda expression Python article.
That’s all for today. We learned quite a bit about Python3 lambda expressions, how to create Lambda expressions in python, and what’s proper lambda syntax. Then we saw what qualifies as an expression, and also learned how to provide default arguments in Python Lambda expression. Finally, we tried out three functions, filter(), map(), and reduce(), to make use of lambdas. A lambda, as compared to a normal function, offers its own benefits. Tell us what you think.