Saturday, 23 November 2024

Why do we require Map, Filter and Lambda Function?



The question comes to every developer mind is that what is function? and why do we need function? in any programming language.
Let's talk about what is function.
Ans: As we know in industry projects there are so many tasks inside one project. All those tasks are depending on each other or sometimes they work individually. There might be situation comes that same task we require more than one time in each module. so, in that case we have to write that specific task code in all those modules again and again. which ultimately increases the code size of project also readability of code also not there and in case any problem occurs then it is very tedious & time-consuming task to debug this code and rectify the bug.
How to overcome all those limitations simply the answer is using function.
Definition: To perform specific task repeatedly we write a block of code in programming that reusable block of code is called as function.

How to create function in python?
simple every function has its specific function name for eg: if i want to create addition function.

def addition ():
    a = 10
    b = 20
    c = a + b
    print ("addition of two number is:", c)

Here, def is the keyword you have to use compulsory while creating the function after that write function name that must be specific as per the logic of function. after that there is ( ): brackets that indicates either function is taking arguments/parameters as an input or not.
Every function process something and may or may not return the output to the caller function.

here is the example of function taking argument as an input. here we are passing two arguments or parameters that is a and b to addition function.

def addition (a, b):
    c = a + b
    print ("addition of two number is:", c)

When there is word function there are 3 things related with function that is:
1. Function Prototype Declaration: In this we are just deciding the prototype of function. Prototype means set of rules so, here we decide what is our function name, how many arguments it takes, after processing the data does this function return output to caller function or not. Example: addition (int, int): Here function name is addition, and it takes two arguments of type integer means we are setting the rule that this function must take data of type integer only.

2. Function Definition: Here in function definition, we write the logic of that specific task so that we can reuse this function again and again in various places inside the project. Example: if we want to add two integer number then function definition as follows:

def addition (a, b):
    c = a + b
    print ("addition of two number is:", c)

3. Function Calling: Function calling means we have to execute this function definition by calling it. so, when we call the function as per function prototype the body of function get execute and we will get the required output. Example: Now, we want to execute addition function then we must call this function like this:
a = 10
b = 20
addition (a, b) 

here in above code, we are accepting the two values from user and pass those values at the time of function calling for processing.

From the above discussion i hope there is no doubt that what is function and why do we require function. Now let's discuss why do we require map, filter and lambda function.

Why do we need Function?
Ans: We need function to overcome the limitation mentioned above as follows:
  1. To avoid repetition of code.
  2. To improve the code readability.
  3. To simplifies the code debugging.
  4. To enables reusability of code.
  5. To modularize the code.

1. What is the use of map function in python?
Ans: A map is built in function in python. We used map function to map specific functions into looping items.
For Example: I want to find out even numbers from the given numbers list and find out the square of all those even number so without using map function i have to write code as follows:

Without map function:

numbers = [11, 22, 33, 44, 55, 66]
evens = []
for n in numbers:
    if n % 2 == 0:
        evens. append(n)
print(evens) # Output: [22, 44, 66]

evens = [22, 44, 66]
square = []
for a in evens:
    a = a*a:
    square. append(a)
print(square)# Output: [484, 1936, 4356]


Total we have to write 12 lines of code. what we have done here, we first create one list of numbers [] where we take six numbers like 11 to 66 in it. Now among this number we want to find even numbers, so we create one more list of evens [] to store even numbers in it.
To find out the even numbers from numbers [] list we iterate or loop through each element of list by using for loop and check using decision making statement if that either this number is even or odd. if the number is even, we append it inside evens list and so on.
Finally processing all the elements from list will get all even numbers inside evens list and lastly, we display all those numbers to user.
Next, we want to find out the square of all those even numbers from the evens list. so once again we want to process each element from the evens [] list one by one so, we need for loop for the same so, accordingly we use for loop take one element from evens list then find out its square and append this square inside square list. finally, we display all the squared element to the user.

With map function:

Now when we use map function then there is no need to use boiler plate of for loop means without using for loop, we can process all elements inside the list with the help of map and filter function.
How, let's see how we use map () in various way and then at last we do above task.

Syntax:
map (function, Iterable)

 1. using map () we can apply specific function to each element of list.

Without Map means using loop how we do this as follows:

numbers = [11, 22, 33, 44]
twice = []
for n in numbers:
    twice. append (n * 2)
print(twice) # Output: [22, 44, 66, 88]

With Map means without using loop how we do this as follows:

numbers = [11, 22, 33, 44]
twice = list (map (lambda x: x * 2, numbers))
print(twice) # Output: [22, 44, 66, 88]

Explanation:
Now question comes to your mind is how map () works and what is lambda and how it works?

First let's discuss what lambda is.
Using lambda, we can avoid the overhead (means defining the function body and writing that one line of code in it) of defining separate function for easy or simple task.

For example, if we want to do twice each element from numbers list without using lambda function then we have to write definition of twice () function then only it is possible like follows:

def Twice (a):
    return a*2

numbers = (1, 2, 3, 4, 5, 6)
result = map (Twice, numbers)
print (list (result) #Output: 2, 4, 6, 8, 10, 12


How lambda does the same task in one line of code instead of 2 lines of code, because inside function definition there is only one line of code which is very simple.

Twice = lambda x: x*2
print (Twice (5) #Output: 10

why use lambda?
Ans: Without using lambda, you would have to define or write a separate named function even for small or simple one line of tasks, making the code unnecessarily lengthy.

So, when to use lambda?
Ans: When we want to create small unnamed (anonymous) functions in a single line which is often used for short-term, simple operations. 

twice = list (map (lambda x: x * 2, numbers))

Now, we understand how lambda works in it and why to use it. so, in above line of code lambda takes x values from numbers [] with the help of map function find out its double and return that it in map object form. finally, we convert this map object into list type and stored it inside twice [] list.

2. Converting data types into strings.

strings = ["11", "22", "33", "44"]
integers = list (map (int, strings))
print (integers) # Output: [11, 22, 33, 44] 

3. Applying a function to multiple Iterables.

mylist1 = [10, 20, 30]
mylist2 = [44, 55, 66]
sum = list (map (lambda a, b: a + b, mylist1, mylist2))
print(sum) # Output: [54, 75, 96]

4. Applying a predefined function: you can pass predefined function to map.

def square_my_num(x):
    return x ** 2

numbers = [ 2, 3, 4]
squared_list = list (map (square_my_num, numbers))
print(squared_list) # Output: [4, 9, 16]











data structures and algorithms Web Developer

No comments:

Post a Comment