What is Lambda Functions in Python and How to Use It
Understanding Lambda functions in Python
An anonymous function is defined without a name in Python. In Python, the def keyword is used to construct conventional functions, whereas the lambda keyword is used to define anonymous functions. As a result, anonymous functions are referred to as lambda functions.
Syntax
lambda arguments : expression
Example:
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
Output:
Use Lambda Function in Python
When you utilise lambda as an anonymous function inside another function, the power of lambda is better demonstrated.
-
Use with filter()
The role of filter()
function in Python is to consider functions and lists as arguments. It makes the filter()
function filter out specific elements from a sequence and show the output as True.
For example, we have list of random numbers and we need to find the numbers that are divisible by 7.
Here is how the filter()
function in Python can be used to do it:
# Python program to find numbers divisible
# by seven from random numbers
# Here is the list of numbers
my_list = [13, 66, 35, 40, 103, 340, 222, 51, 70]
# using filter to compare and find numbers
# divisible by seven or not
result = list(fliter(lambda x: (x % 7 == 0), my_list))
# print the result
print(result)
list(filter(lambda x: x>18, df['age']))
Output:
-
Use with map()
Map works very much like apply() in that it modifies values of a column based on the expression.
#Double the age of everyone
df['double_age'] =
df['age'].map(lambda x: x*2)
-
Number of Arguments
A function must be called with the right number of parameters by default. That is, if your function requires two parameters, you must call it with two arguments, not more or fewer.
-
Arbitrary Arguments, *args
In Python, some specific symbols are used for passing arguments to functions. Args is used for non-keyword arguments in Python, with the special symbol being asterisk (*).
Code:
def myfunction(*a):
print("python" + kid[3]
myfunction("a", "b", "c",”d”)
python d
-
Arbitrary Keyword Arguments, **kwargs
You must insert two asterisks ** before the parameter name in the function declaration if you don't know how many keyword arguments will be provided in your function.
As a result, the function will get a dictionary of parameters and will be able to retrieve the objects as follows:
Code:
def myfunction(**k):
print("python " + k["pname"])
myfunction(name = "jodhpur", pname = "wscube")
Output:
QUIZ!
