An anonymous function can be defined as function that is which is without a name that means the function name is empty.
While normal functions are defined using the def keyword, we define anonymous functions using the lambda keyword.
Hence, anonymous functions are also called lambda functions
Syntax:
lambda [arg1,arg2,..]:[expression]
lambda is a keyword/operator and can have any number of arguments.
An expression here is anything that can return some value.
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”)
Assignment statements cannot be used in lambda , because they don’t return anything, not even None (null).
Simple things such as mathematical operations, string operations etc. are OK in a lambda.
Function calls are expressions, so it’s OK to put a function call in a lambda, and to pass arguments to that function.
Even functions that return None, like the print function in Python version3, can be used in a lambda.
Single line if – else is also allowed as it also evaluates the condition and returns the result of true or false expression
Suppose, we want to make a function which will calculate sum of two numbers.
In normal approach we will do as shown below:
def add(a,b):
return a+b
In case of lambda function we will write it as:
lambda a,b: a+b
A very common doubt is that when we can define our functions using def keyword , then why we require lambda functions ?
The most common use for lambda functions is in code that requires a simple one-line function, where it would be an overkill to write a complete normal function.
We will explore it in more detail when we will discuss two very important functions in Python called map( ) and filter( )
There are 2 ways to use a Lambda Function.
1. Using it anonymously in inline mode
2. Using it by assigning it to a variable
print((lambda a,b: a+b)(2,3))
Output:
5
sum=lambda a,b: a+b
print(sum(2,3))
print(sum(5,9))
Output:
5
14
What is happening in this code ?
import math
sqrt=lambda a: math.sqrt(a)
print(sqrt(25))
print(sqrt(10))
Output:
5.0
3.1622776601683795
Example:
lambda function that accepts 2 arguments and returns the greater amongst them
maxnum=lambda a,b: a if a>b else b
print("max amongst 10 and 20 :",maxnum(10,20))
print("max amongst 15 and 5 :",maxnum(15,5))
Output:
max amongst 10 and 20 : 20
max amongst 15 and 5 : 15
map()
is a function which takes two arguments:
r = map(func, iterable)
The first argument func is the name of a function and the second argument , iterable ,should be a sequence (e.g. a list , tuple ,string etc) or anything that can be used with for loop. map()
applies the function func to all the elements of the sequence iterable
Example:
Write a function called inspect( ) that accepts a string as argument and returns the word EVEN if the string is of even length and returns it’s first character if the string is of odd length.
Now call this function for first 3 month names
def inspect(mystring):
if len(mystring)%2==0:
return "EVEN"
else:
return mystring[0]
months=["January","February","March"]
print(list(map(inspect,months)))
Output:
['J', 'EVEN', 'M']
Like map( ) , filter( ) is also a function that is very commonly used in Python .
The function filter ( ) takes 2 arguments:
filter(function, sequence)
The first argument should be a function which must return a boolean value
def f1(num):
return num*num
mynums=[1,2,3,4,5]
print(list(filter(f1,mynums)))
Output:
[1,2,3,4,5]
Ideally , the function passed to filter( ) should return a boolean value. But if it doesn’t return boolean value , then whatever value it returns Python converts it to boolean . In our case for each value in mynums the return value will be it’s square which is a non-zero value and thus assumed to be True. So all the elements are returned by filter()
The best use of Lambda Expression is to use it with map( ) and filter( ) functions
Recall that the keyword lambda creates an anonymous function and returns it’s address.
So , we can pass this lambda expression as first argument to map( ) and filter() functions , since their first argument is the a function object reference
In this way , we wouldn’t be required to specially create a separate function using the keyword def
Example:
Write a lambda expression that accepts a string as argument and returns it’s first character
Now use this lambda expression in map( ) function
to work on for first 3 month names
months=["January","February","March"]
print(list(map(lambda mystring: mystring[0],months)))
Output:
['J', 'F', 'M']
name=input("Enter your name:")
vowels=list(filter(lambda ch: ch in "aeiou" ,name))
if len(vowels)==0:
print("No vowels in your name")
else:
print("Vowels in your name are:",vowels)
Output:
Enter your name: Chitranshi
Vowels in your name are: ['i', 'a', 'i']