Today I’m going to talk about lambda functions, which are commonly referred to as expressions in Python programming.
This article to share from huawei cloud community “from scratch to learn python | what is Lambda functions and how to use them?” , original author: Yuchuan.
A name is a convention used to refer to or address any entity. Almost everything around us has a name. Programming is in line with this. But does it have to be named? Or can you have “anonymous” goods? The answer is yes. Python provides Lambda functions, also known as anonymous functions, that are virtually nameless. So let’s continue learning these “mysteries of anonymity” in Python in the following order.
-
Why are Python Lambda Functions required?
-
What are Python Lambda Functions?
-
How to write Lambda Functions?
-
How do Anonymous functions reduce the size of the code?
-
Python Lambda functions within user defined functions
-
How to use Anonymous functions within:
filter()
map()
reduce()
So, let’s get started 🙂
Why use Python Lambda functions?
The main purpose of anonymous functionality becomes apparent when you only need to use it once. They can be created wherever needed. For this reason, PythonLambda functions are also called throw functions and are used in conjunction with other predefined functions such as filter (), map (), and so on. With ordinary Python functions.
To demonstrate this, let’s move on to Python Lambda functions.
What are Python Lambda functions?
Python Lambda functions are functions that do not have any names. They are also called anonymous or nameless features. The word “lambda” is not a name, but a keyword. This keyword specifies that subsequent functions are anonymous.
Now that you know what these anonymous functions refer to, let’s take a closer look at how to write these PythonLambda functions.
How do I write Lambda functions in Python?
Lambda functions are created using lambda operators with the following syntax:
Syntax:
Lambda arguments: expressions
Python lambda functions can have any number of arguments, but only ** one expression is required. ** Input or argument variables can start at 0 and can reach any limit. Just like any other function, it’s nice to have lambda functions with no input. Therefore, you can use lambda functions in any of the following formats:
Example:
Lambda: “Specify purpose”
Here, lambda functions take no arguments.
Example:
Ramda a 1: “Specified use of 1”
Here, lambda takes one input, 1.
Similarly, you can have lambda a 1, a 2, a 3.. A n.
Let’s take a few examples to prove the point:
Example 1:
a = lambda x: x*xprint(a(3))
Copy the code
Output: 9
Example 2:
A = lambda x,y: x*yprint(a(3,7))Copy the code
Output: 21
As you can see, I’ve given two examples here. The first example uses only a lambda function with an expression, while the second example has two arguments passed to it. Notice that both functions have an expression followed by arguments. Therefore, lambda functions cannot be used where multiline expressions are required.
Ordinary Python functions, on the other hand, can use any number of statements in their function definition.
How do anonymous functions reduce code size?
Before comparing the amount of code required, let’s first write down the syntax of a regular function, and then compare it to the syntax of a lambda function described earlier.
Any regular function in Python is defined using the def keyword, as follows:
Syntax:
Def function_name (parameters) :
statements
As you can see, lambda functions require much less code than normal functions.
Let’s rewrite the previous example with the normal functions we have now.
Example:
def my_func(x): return x*xprint(my_func(3))
Copy the code
Output: 9
As you can see, in the example above, we need to use the return statement in my_func to compute the square of 3. Lambda functions, in contrast, do not use this return statement, but instead write the body of the anonymous function on the same line as the colon followed by the function itself. Therefore, the size of the function is less than the size of my_func.
However, the lambda function in the example above is called with some other variable A. This is done because these functions are nameless and therefore need to be called by some name. But the fact that you use nameless functions like this seems confusing when you actually need to assign other names to call them? Of course, after assigning the name A to my function, it is no longer nameless! The correct?
That’s a fair question, but the point is, it’s not the right way to use these anonymous functions.
Anonymous functions are best used in other higher-order functions that take functions as arguments or return functions as output. To prove the point, let’s now move on to the next topic.
Python Lambda functions in user-defined functions:
As mentioned above, lambda functions can be used in other functions to mark the greatest advantage.
The following example consists of new_func, which is a regular Python function with a single argument x. This parameter is then added to the unknown parameter y supplied via the lambda function.
Example:
def new_func(x): return(lambda y: x+y)t=new_func(3)u=new_func(2)print(t(3))print(u(3))
Copy the code
Output:
65
As you can see, in the example above, every time we use new_func (), the lambda function that exists in new_func is called. Each time, we can pass a separate value to the parameter. Now that you know how to use anonymous functions in higher-order functions, let’s move on to one of its most popular uses in filter (), map (), and reduce () methods.
How to use anonymous functions in filter (), map (), and reduce () :
The anonymous function ** in filter () : **
Filter () :
The filter () method is used to filter a given iterables (list, collection, etc.) with the help of another function passed as an argument to test whether all elements are true or false.
The syntax for this function is:
Syntax:
Filters (functions, iterable)
Now consider the following example:
Example:
My_list = [2,3,4,5,6,7,8]new_list = list(filter(lambda a: (a/3 == 2), my_list) print(new_list)Copy the code
Output: [6]
In this case, my_list is a list of iterable values that are passed to the filter function. This function uses a lambda function to check if there are any values in the list (divided by 3 equals 2). The output consists of a list of expressions that satisfy the existence of anonymous functions.
Map () :
The map () function in Python is a function that applies a given function to all iterable objects and returns a new list.
Syntax:
Map (function, iterable)
Let’s use a lambda function in map () as an example:
Example:
My_list = [2,3,4,5,6,7,8]new_list = list(map(lambda a: (a/3! = 2), li))print(new_list)Copy the code
Output:
[True, True, True, True, False, True, True]
The above output shows that as long as the value of an iterable variable is divided by 3, it does not equal 2, and the result returned should be True. Therefore, for all elements in my_list, it will return true (except for the value 6) when the condition changes to False.
Decrease () :
The reduce () function is used to apply some other function to the list of elements passed to it as an argument and ultimately return a single value.
The syntax for this function is as follows:
Syntax:
Reduce (function, order)
Example:
From functools import reducereduce(lambda a,b: a+b, [23,21,45,98])Copy the code
The following illustration illustrates the example above:
Output: 187
The output makes it clear that all elements of the list are added consecutively to return the final result.
Click to follow, the first time to learn about Huawei cloud fresh technology ~