I was startled by Lambda functions when I first saw them in Python and assumed they were only for senior Pythonists. In fact, python guides for beginners praise the understandable syntax of the language, but Lambada did not seem particularly user-friendly.
Using them became less threatening once I understood the general syntax and looked at some easy use cases.
The Lambda function is similar to any other Python function in terms of syntax. However, it is defined without a name and is included in a single line of code.
A lambda function can be described as an anonymous function. Generally, a varied count of arguments is required although it can have only one expression.
Using Lambda in Python
The syntax of the Lambda function is as follows.
For a given argument, a lambda function evaluates an expression. You provide a value (argument) to the function and then the action (expression). Lambda must be the first keyword. The argument and the expression are separated by a full colon (:).
- Lambda Arguments: Expression
- After the expression is performed, the result is returned.
Contrast between standard Python function and Lambda function
The argument, a, is the argument in the sample code below, and the expression a + a is the expression.
# Normal python function def normalFunction(a): return a+a
# Lambda function lambda a: a+a
We intend to add 50 to a given x argument and return the result obtained in this example.
a = lambda x : x + 50 print(a(20))
In this example, we will multiply the argument x with the argument y and as a result we will return the results.
a= lambda x, y: x * y print(x(10, 20))
This example demonstrates the use of arguments x, y, and z to summarize and return the results given.
lamb_val =lambda a, b, c : a + b+ c print(lamb_val(5, 6, 2))
Lambda functions, like def functions, accept any argument.
- Keyword Arguments: In calling a function, a keyword argument is an argument followed by an identifier (for example, name =).
Arguments in the Name: Example
(lambda x, y=3, z=5: x*y*z)(7)
Variable list of arguments: Example
(lambda x, y=3, z=5: x*y*z)(x=7)
List of Keyword Argument Variables: Example
(lambda *args : sum(args))(3,5,7)
- Non-keyword arguments (also called placement arguments): A keyword-free argument is not a keyword argument.
(lambda x,y,z : x*y*z)(3,5,7)
Why use the Lambda function?
The best use of a lambda function is to use it as an anonymous function within another function. For example, if your function needs one argument and the given argument is multiplied by a number, it is unknown.
def newFunc(a): return lambda b : b * n
By signing the function above, we can create a function that multiplies any number given as an argument.
def newFunc(a): return lambda b : b * a double_val = newFunc(2) print(double_val(24))
Alternatively, you can use the exact definition of the function to invent a function that quadruples the number provided as follows.
def newFunc(a): return lambda b : b * a quadruple_val = newFunc(4) print(quadruple_val(3))
You can use the exact function definition in the same program to create the two functions above to multiply and quadruple the value provided.
def newFunc(a): return lambda b : b * a quadruple_val = newFunc(4) double_val = newFunc(2) print(double_val (5)) print(quadruple_val (5))
Let’s get into some details about what the Python community considers good and negative in Lambda functions.
Suitable for simple and easy-to-understand logical procedures. It also improves code readings.
When you only need to function once, this is a good option.
They can only make one expression at a time. It is not possible to combine several separate operations into a single lambda function.
In a standard Def function, operations that span more than one row are incorrect, such as nested conditional operations. Use a named function instead if you need a minute or two to figure out the code.
Plus, it’s not good because unlike a typical Def function, you can not use the doc string to explain all the inputs, operations, and outputs.
When should Lambda not be used?
In a manufacturing environment, never write sophisticated Lambda functions. Deciphering your code will be extremely difficult for coders who hold it. If you often write sophisticated phrases, setting up a correct function is a much better approach. Remember that a simple code is always better than a complex code as a recommended practice.
Normal functions compared to labs
Labs, as previously stated, are essentially unrecognizable functions. In other words, these are anonymous (and therefore, anonymous) functions. Below are the differences between labs and standard functions in Python.
- In the body of a lambda function, there can be only one expression.
- The body of a normal function can contain a number of expressions and statements.
- Lambs do not have a connected name. As a result, they are sometimes referred to as anonymous functions.
- Name and signature are required for standard functions.
- Because the body is automatically returned, Lambda does not have a return statement.
- A return statement should be included in functions that require a return of value.
What are the differences?
The main distinction between a lambda and a standard function is that the lambda evaluates only one expression and returns a function object.
As a result, we may name the result of a lambda function and use it in our program, just as we did in the previous example.
For the example given, a standard function might look like this.
def adder (x, y): return x + y print (adder (1, 2))
We must give the function a name that will return the result when we call it. The return statement is not used in the lambda function because it has only one expression, which is always returned by default. You do not even have to assign a lambda because it can be called immediately. When we employ labs with the built-in functions of Python, they become even more powerful.
You may still be confused about how the lambda changes from a function that returns a single expression. There is not much difference in the level of the interpreter. The interpreter treats each Lambda function you define in Python as a standard function, which may surprise you.
In conversion to bytecode, both settings are handled in the same way by a python translator, as shown in the diagram. Because Python saves the name lambda, you can not use it, but any other function name will produce the same bytecode.
When to use Lambda functions?
Consider when to use lambda functions. Note that lambda functions are often used with Python classes that accept a function as an argument, such as map () and filter (). The other name for such functions is high order functions.
This refers when a Lambda function is applied to a single value.
The function was created and then immediately activated in the code above. This is an example of a function that is triggered immediately or IIFE.
screen out() Is a built-in Python library that returns only entries that meet specific requirements. The syntax of this function is as follows.
Filter (function, repeatable).
Any sequence, such as a list object, group, or series, can be used as a return.
The example below looks for even numbers in the list.
The filtering method returns a ‘filtering object’, which must be embedded in the list to return the values.
list_vals = [1,2,3,4,5,6,7,8,9] filter(lambda x: x%2==0, list_vals) # output list(filter(lambda y: y%2==0, list_vals)) # output
ages = [13, 90, 17, 59, 21, 60, 5] adults = list(filter(lambda age: age>18, ages)) print(adults)
from here() Is a built-in Python library that has the following syntax:
Map (function, repeatable)
This produces a different list where a function changed each value in the original list. Each integer in the list is quadrupled in the example below.
list_vals = [1,2,3,4,5,6,7,8,9] quad_vals = map(lambda y: pow(y,4), list_vals) list(quad_vals)
Lamb in reduce ()
Reduce is similar to map () in that it applies an action to each element in the sequence. The reduce () method repeats the element pairs of the list. Reduce () will take the lambda function and the list as arguments. However, its process is different from that of the map. The reduce () method takes the following steps to calculate output:
Step 1: Apply the defined action to the first two items of the sequence.
Step 2: Save the result
Step 3) Use the recorded result and the next component in the sequence to complete the operation.
Step 4) Continue until there are no more elements.
It also has two additional parameters:
A function that specifies the action to be performed.
A series of events (each iterator such as lists, treatments, etc.)
Here is an example of a program that returns the product of all the components in the list.
from functools import reduce sequences = [3,4,5,6,7] product = reduce (lambda a, b: a*b, sequences) print(product)
Using Lambda inside reduce
from functools import reduce list1 = [1,2,3,4,5,6,7,8,9] sum = reduce((lambda x,y: x+y), list1) print(sum)
Explanation of the code:
Reduce must be imported from the functools module.
Here, we create a list of sequences, which includes specific numbers.
We create a variable called a product to track the depreciated value.
The lambda function executes each item in the list. As in the last result, it will yield the product of this number.
The result of the reduction function must be printed.
Lambda functions for conditional statements
Conditional statements, such as “if … other”, are also supported by Lambda functions. Strong learning functions as a result.
Let’s imagine we need to label people in the family data frame as ‘adult’ or ‘child’. We may do this by applying a lambda function to our data frame:
df['category']=df['age'].apply(lambda x: 'Adult' if x>=18 else 'Child')
Lambda can be used to write higher order functions
An additional function can be passed as an argument to the lambda function.
Consider a nested Lambda function, which is a Lambda function within another Lambda function.
# Define a lambda function that can take another lambda function (func1). high_order = lambda x, lmbfunc: x*lmbfunc(x) # The inner lambda function is defined when calling the high_order. high_order(10, lambda x : x*x) #> 1000
Python Lambda with several statements
Some statements are forbidden in Lambda functions, but we can construct two Lambda functions and then call the second Lambda function as a parameter to the first function. Let’s use Lambda to discover the second maximum element.
List = [[2,3,4],[1, 4, 16, 64],[3, 6, 9, 12]] # Sort each sublist sortList = lambda x: (sorted(i) for i in x) # Get the second largest element secondLargest = lambda x, f : [y[len(y)-2] for y in f(x)] res = secondLargest(List, sortList) print(res)
We built a Lambda function that sorts each sub-list of the list given in the example above. The second lambda function takes this list as an argument and returns the member n-2 from the sorted list, where n is the length of the sub-list.
A series object is a data frame column, or, in other words, a sequence of values with matching metrics. Within a Pandas data framework, Lambda functions can be used to change values.
Let’s create a dummy data frame with family members.
'Name': ['Luke','Gina','Sam','Emma'], 'Status': ['Father', 'Mother', 'Son', 'Daughter'], 'Birthyear': [1976, 1984, 2013, 2016], })
Pandas’ Lambda with Apply () function
This function performs an action on each column component.
We deduct the year of birth of each member from the current year to determine his or her current age. The expression 2021 (current year) minus the value used in the Lambda function below. a refers to the value in the year of birth column, and the expression is 2021 (current year) less the value.
df['age'] = df['Birthyear'].apply(lambda a: 2021-a)
Lambda with Python’s Filter () function
The Python Filter () method can be used with Lambda. It accepts two arguments: one is a Lambda function with conditional expression, and the other is a repeatable, series object in our case. It gives you a list of values that meet the criteria.
list(filter(lambda a: a>20, df['age'])) ###Output [45, 37]
Lambda with Pandas Map () function
In the same way that just as apply () changes the values of a column based on the expression, Map changes the values of a column.
# Double the age of everyone df['double_age'] = df['age'].map(lambda x: x*2)
Lambda on Dataframe object
Unless we want to edit the entire data frame with a single expression, we typically use Lambda functions on specific columns (series objects) rather than the complete data frame.
For example, if all values are rounded to one decimal place, all columns must be of float or int datatypes type because round () does not run on strings.
df2.apply(lambda x:round(x,1)) # Returns an error if some # columns are not numeric
We apply it to a data frame and select the columns to edit in the Lambda function in the example below. Note that we must use the = 1 axis to apply the column-by-column equation.
# convert to lower-case df[['Name','Status']] =df.apply(lambda x: x[['Name','Status']].str.lower(), axis=1)
When given a name for the lambda function
The Python-style PEP8 device prevents this because Lambda produces an anonymous function that is not intended for storage. If you want to save the operation for later use, use the standard Def function instead.
# sample bad application triple = lambda a: a*3 # sample good application def triple(a): return a*3
import pandas as pd df = pd.DataFrame([[1,2,3],[4,5,6]],columns = ['First','Second','Third']) df['Forth']= df.apply(lambda row: row['First']row['Second'] row['Third'], axis=1) df
Use Lambda functions to provide functions to other Lambda functions
Using processes that accept only number one argument, such as abs, is no longer essential with Lambda because you can enter the action directly into map () or application ().
#Bad map(lambda y:abs(y), list_vals) #Good map(abs, list_vals) #Good map(lambda y: pow(y, 3), float_nums)
Functions within Lambda functions should, in theory, take two or more parameters. Pow (number, power) and round (number, ndigit) are two examples. You can try different built-in Python functions to see which ones require Lambda functions in this mode.
When multiple lines of code are more readable, avoid using Lambda functions.
For example, when you use if-else statements within the lambda function. In this tutorial, we used the example below.
# Conditional Lambda statement df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')
With the code below, you may get the same results. This is our preferred method because you may have an infinity of conditions, and the code is easy to understand.
df['Gender'] ='' df.loc[(df['Status'] == 'father') | (df['Status'] =='son'), 'Gender'] ='Male' df.loc[(df['Status'] == 'mother') | (df['Status'] == 'daughter'), 'Gender']='Femele'
Many programmers who do not like labs believe that clearer lists, built-in functions, and standard libraries can be used instead. Alternatives to the map () and filter () functions include generator expressions similar to list understanding.
Whether you use Lambda functions in your code or not, you need to know what they are and how they work because you will no doubt encounter them in other people’s code.