How to use Lambda in Python
Table of Contents
I was terrified by lambda functions when I first saw them in Python and assumed they were only for senior Pythonistas. In fact, beginner python tutorials praise the language’s intelligible syntax, but lambdas didn’t appear to be particularly user-friendly.
Using them became less intimidating once I grasped the general syntax and looked at some easy use cases.
A lambda function is similar to any other Python function in terms of syntax. However, it is defined without a name and is contained in a single line of code.
A lambda function can be based be described as an anonymous function. Usually, it takes a varied count of arguments though it can only have one expression.
Using Lambda in Python
The syntax of a 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 operation (expression). Lambda must be the first keyword. The argument and the expression are separated by a full colon (:).
- lambda argument(s): expression
- After the expression is executed, the result is returned.
Contrasting a normal Python Function and a Lambda Function
The argument, a, is the argument in the example 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 argument x and return the resultant result in this example.
a = lambda x : x + 50 print(a(20))
In this example, we multiply argument x with argument y and consequently return the results.
a= lambda x, y: x * y print(x(10, 20))
This example demonstrates using arguments x, y, and z to summarise and return the given results.
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 a function call, a keyword argument is an argument followed by an identifier (e.g., name=).
Named Arguments: 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)
Variable list of keyword arguments: Example
(lambda *args : sum(args))(3,5,7)
- Non-keyword arguments (also called positional arguments): A non-keyword argument is not a keyword argument.
(lambda x,y,z : x*y*z)(3,5,7)
Why should you use a Lambda Function?
The best use of a lambda function is using it as an anonymous function within another function. For instance, if your function needs one argument and the given argument is multiplied by a number, that is unknown.
def newFunc(a): return lambda b : b * n
Using the above function signature, we can create a function that doubles any number given as the 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 come up with 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 both functions above to double and quadruple the provided value.
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 about lambda functions.
Suitable for straightforward, easy-to-understand logical procedures. It also improves the readability of the code.
When you only need a function once, this is a good option.
They can only make one expression at a time. Multiple separate operations cannot be combined into a single lambda function.
In a regular def function, operations that span more than one line are wrong, such as nested conditional operations. Use a named function instead if you need a minute or two to understand the code.
In addition, it isn’t good because, unlike a typical def function, you can’t use a doc-string to explain all the inputs, operations, and outputs.
When should Lambda not be used?
In a production environment, you should never write sophisticated lambda functions. Decrypting your code will be extremely tough for coders who maintain it. If you frequently write sophisticated one-liner expressions, defining a proper function is a much better approach. Remember that simple code is always preferable to complex code as a recommended practice.
Regular functions vs lambdas
Lambdas, as previously stated, are essentially functions that don’t have an identification attached to them. In other words, they are anonymous functions (hence, anonymous). The following shows the differences between lambdas and standard functions in Python.
lambda b : b + b
def (a) : return a + a
- In the body of a lambda function, there can only be one expression.
- The body of a regular function can contain several expressions and statements.
- Lambdas don’t have a name attached to them. As a result, they’re sometimes referred to as anonymous functions.
- A name and signature are required for regular functions.
- Because the body is automatically returned, lambdas do not have a return statement.
- A return statement should be included in functions that require returning a 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.
Consequently, we may name the lambda function’s result and utilize it in our program, just as we did in the previous example.
For the given an example, a regular 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. A return statement isn’t used in a lambda function because it only has one expression, always returned by default. You don’t even need to assign a lambda because it can be called right away. When we employ lambdas with Python’s built-in functions, they become even more powerful.
You may still be perplexed about how lambdas vary from a function that returns a single expression. There isn’t much of a difference at the interpreter level. The interpreter treats any lambda function you define in Python as a regular function, which may surprise you.
When converted to bytecode, the two definitions are treated the same way by the python interpreter, as shown in the diagram. Because Python reserves the name lambda, you can’t use it, but any other function name will produce the same bytecode.
When to use Lambda functions?
Consider when lambda functions should be used. Note that lambda functions are frequently used with Python classes that accept a function as an argument, such as map() and filter(). The other name for these kinds of functions is Higher-order functions.
It refers to when a lambda function is applied to a single value.
(lambda y: y*6)(5)
The function was created and then immediately executed in the code above. It is an example of an instantaneously invoked function expression or IIFE.
Filter() is a Python built-in library that only returns values that meet specific requirements. The syntax of this function is as follows.
Any sequence, such as a list, set, or series object, can be used as the iterable.
The example below searches for even numbers in a list.
The filter method returns a ‘Filter object,’ which must be encapsulated with a 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)
Map() is a built-in Python library that has the following syntax:
map (function, iterable)
It produces a modified list in which a function has changed each value in the original list. Every 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)
lambdas in reduce()
Reduce is similar to map() in that it applies an operation to each element in a sequence. The reduce() method performs a repeating operation on the list’s pairs of elements. Reduce() will take the lambda function and the list as arguments. Its process, however, differs from that of the map. The reduce() method takes the following steps to compute an output:
Step 1: Apply the defined operation to the sequence’s first two items.
Step 2: Save the outcome
Step 3) Use the recorded result and the next element 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 taken.
a series of events (any iterator like lists, tuples, etc.)
Here’s an example of a program that returns the product of all the elements in a 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 Code:
Reduce from the functools module should be imported.
Here, we create a sequences list, which has specific numbers.
We make a variable called product to keep track of the reduced value.
A lambda function executes each list item. As with the last result, it will yield the product of that number.
The outcome of the reduction function should be printed.
Lambda Functions for Conditional Statements
Conditional statements, such as “if… else”, are likewise supported by Lambda functions. Lambda functions are powerful as a result of this.
Let’s imagine we need to label people in the family dataframe as ‘Adult’ or ‘Child.’ We may do this by applying the lambda function to our dataframe:
df['category']=df['age'].apply(lambda x: 'Adult' if x>=18 else 'Child')
Lambda can be used to write higher-order functions
Another function can be passed as an argument to a lambda function.
Consider a nested lambda function, which is a lambda function inside 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 Multiple Statements
Multiple statements are not allowed in lambda functions, but we can build 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’ve constructed a lambda function that sorts each sublist of the given list in the example above. The second lambda function takes this list as an argument and returns the n-2 member from the sorted list, where n is the length of the sublist.
A Series object is a data frame column, or, to put it another way, a succession of values with matching indices. Inside a Pandas dataframe, lambda functions can be used to alter values.
Let’s make a dummy dataframe with family members.
'Name': ['Luke','Gina','Sam','Emma'], 'Status': ['Father', 'Mother', 'Son', 'Daughter'], 'Birthyear': [1976, 1984, 2013, 2016], })
Pandas’ Lambda with the Apply() function
This function performs an operation on each column element.
We deduct each member’s birth year from the current year to determine their current age. The expression 2021(current year) minus the value is used in the lambda function below. a refers to a value in the birthyear column, and the expression is 2021(current year) minus the value.
df['age'] = df['Birthyear'].apply(lambda a: 2021-a)
Lambda with Python’s Filter() function
Python’s Filter() method can be used with Lambda. It accepts two arguments: one is a lambda function with a condition expression, and the other is iterable, a 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 Map() function by Pandas
In the same way, as apply() alters the values of a column based on the expression, Map modifies 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 wish to edit the entire data frame with a single expression, we usually utilize Lambda functions on specific columns (series objects) rather than the whole data frame.
For example, if all values have to be rounded to one decimal place, all columns must be float or int datatypes because round() does not operate on strings.
df2.apply(lambda x:round(x,1)) # Returns an error if some # columns are not numeric
We apply it to a dataframe and select the columns to edit in the Lambda function in the example below. Note that we must use axis=1 to apply the equation column-by-column.
# convert to lower-case df[['Name','Status']] =df.apply(lambda x: x[['Name','Status']].str.lower(), axis=1)
scenarios that have been discouraged
When a Lambda function is given a name
The PEP8 python style standard discourages this since Lambda produces an anonymous function that isn’t meant to be stored. If you want to save the operation for later usage, use a regular 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
Using Lambda functions to provide functions to other Lambda functions
Using processes that only accept one number-argument, such as abs, is no longer essential with Lambda because you can feed the operation directly into map() or apply().
#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 out different built-in Python functions to check which ones require Lambda functions in this situation.
When numerous lines of code are more readable, avoid using Lambda functions.
For instance, When you use if-else statements inside a lambda function. In this tutorial, we utilized 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 outcomes. It is our preferred method because you may have an infinite number 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 dislike Lambdas believe that more clear list comprehensions, built-in functions, and standard libraries can be used instead. Alternatives to the map() and filter() functions include generator expressions akin to list comprehensions.
Whether or not you use Lambda functions in your code, you should know what they are and how they work because you will undoubtedly encounter them in other people’s code.