Sunday, 30 September 2018

Lambda, Map and Filter functions

Lambda functions


You might be familiar with the way functions are defined in Python. For example this is a sample function to square a number:

def pow2(a):
    return a**2

This function would return square of any input number.

pow2(10) #Will correctly return 100 as the output

We can strip of lots of unnecessary details from the pow2 function. The most important part of the function is to return 'num**2' which will square the number. Rest of the details like name, keywords are not adding much to the function.

Initially, the function can be written in a single line as follows:

def pow2(a):return a**2

Then, we can strip of the keywords, replacing them with the single lambda function that would look like:

lambda num: num**2

This above lambda function does the same functionality as our 'pow2' function.

To apply this lambda function to a sequence of items (Python list), we are going to use the map function

Map function


Map function comes into picture to apply a function to individual elements of a sequence. 

We can apply the regular functions as well as lamdba function using map function.

The regular function to get the individual items in a list squared goes like this:

list_a = [1,3,5,7,11] #define Python list

map(pow2,list_a) #Using map function, apply the earlier defined pow2 function to all the items of the list

The output would be a map function at a particular place in a memory. 

<map at 0x10cb3e9f390>

But to obtain the output you have to put them into a list. Something like this:

list(map(pow2,list_a)) #Gives an output of [1,9,25,49,121]

Now let us map the lambda function as well:

list(map(lambda num:num*5,list_a)) #Gives an output of [5,15,25,35,55]


Filter function


Now, if we have to filter out numbers divisible by 3 from our original list:

list(filter(lambda num:num%3 != 0,list_a)) 

#Filters out elements that are divisible by 3. 
#Output is [1,5,7,11] as 3 is filtered out.

Nested filter and map function would look like:

list(filter(lambda num:num%3 != 0,map(lambda num:num*5,list_a)))

So far we have covered some of the basic functionalities in Python in order to prepare you to get started in the world of data science. Next post will be a short one containing a set of Python code / exercise. If you are able to answer most of those questions, then you are good to proceed further. Otherwise, I would recommend you to revise this introductory stuff in a detailed manner before continuing with some of the advanced topics like Numpy and Pandas.

No comments:

Post a Comment