python


Python Anonymous Functions


What Are Anonymous Functions ?

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.
But it can have only one expression.
Python evaluates the expression and returns the result automatically.


What is an Expressions?

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”)


So what can be written in lambda expressions?

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


How to create lambda functions?

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


Why to create lambda functions?

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( )


How to use lambda functions?

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


Using it as anonymous function

print((lambda a,b: a+b)(2,3))
Output:

5

Using it by assigning it to a variable

sum=lambda a,b: a+b

print(sum(2,3))
print(sum(5,9))
Output:

5
14
What is happening in this code ?
The statement lambda a,b:a+b , is creating a FUNCTION OBJECT and returning that object . The variable sum is referring to that object. Now when we write sum(2,3), it behaves like function call
Example:

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

What is Map Function?

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']


The filter() function

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
The second argument should be a sequence of items.
Now the function filter( ) applies the function passed as argument to every item of the sequence passed as second argument.
If the function returned True for that item , filter( ) returns that item as part of it’s return value otherwise the item is not returned
Example:

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()


Using Lambda Expression With map( ) And 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']


Using Lambdas With filter( )

Example:
Write a lambda expression that accepts a character as argument and returns True if it is a vowel otherwise False
Now ask the user to input his/her name and display only the vowels in the name . In case the name does not contain any vowel display the message No vowels in your name

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']