A brief description of Lambda function, Map, Filter, and Reduce in Python

Python is an object-oriented, high-level programming language. It is interpreted by an interpreter and is dynamic in nature. Python is widely used due to its easy-to-write and understandable syntax.
What about writing a function in one line for the tasks or applying an expression without iterating the iterable? Seems magical…. but there is no magic, it's just the potential of the Python language.
Lambda functions, Map, Filter and Reduce are some basic components of Python yet very useful to increase your productivity.

Before diving into the lambda functions, let’s see what the functions are:

  • Functions are an organised and reusable sequence of code that is used to carry out some task.

  • Functions are needed to be called to execute them and get the task done. The function can be called by writing its name and then followed by round brackets “()”, in which arguments are passed if required. Now if the functions are returning some value then it can be stored in a variable for future use.

  • There are mainly two types of functions:
    1) Inbuilt function
    2) User defined function

  • Inbuilt functions are the functions which are provided by the Python language. They can be executed just by calling them in our function.

  • User-defined functions are needed to be defined to use them. A function can be defined by using the keyword “def” in Python, followed by the function name, and then round brackets like “()” and then a colon “:”. In the round brackets, we can pass the arguments and then do some processing in the body and return results.

  • Functions are used to make the code look modular. The program becomes easily understandable and manageable. Functions break down the code into smaller reusable chunks.

  • The syntax of the Python function is as follows:

  • An Example of a function is as follows:

      def multiply(x, y):
        z = x * y
        return z
    
      m = multiply(4, 5)
      print(m)
    
This gives the output: 20.
Here 4 and 5 are taken as arguments, then the result is stored in m and then its printed to console.

Lambda Function:

  • A lambda function is a one-liner anonymous function without any name.

  • Lambda functions are the user-defined functions.

  • It is used for small tasks and is mainly combined with map, filter, and reduce to increase readability.

  • A lambda function takes arguments as a normal function and returns a value. A function object can be created to store the output of the lambda function.

  • The syntax of the lambda functions is as follows:

  • Some examples of lambda functions are as follows:

      f = lambda x, y : x + y
      print(f(3, 2))
    
    This gives the output: 5
    The above example adds the arguments given to the function. Here 3 is taken as x and 2 is taken as y. Then the operation is performed on x and y and the result is returned. Notice that here one or more than one argument can also be given.
      f = lambda x: x**2
      print(f(3))
    
This gives the output: 9
The above code gives the square of the number passed in it.

Map():

  • A Map is used to perform a function on each item of an iterable like list, tuple, etc.

  • It takes an iterable as input and returns a map object, which can be converted to an iterable for the desired output.

  • Every item in the iterable is provided to a function, and the output is then placed in the same location.

  • The syntax of a Map is as follows:

  • Some examples of map are as follows:

      def getDouble(w):
        return w*2
    
      l = [1, 2, 3, 4]
      r = list(map(getDouble, a))
      print(r)
    
This gives the output: [2, 4, 6, 8]
The above code doubles each element of the list. Here it takes the first element then doubles it, then takes the next element and doubles it… Likewise, it goes till the end of the list. Finally, a map object is typecasted into the list to see the output as a list.

Notice that we can also use the lambda function instead of the normal function.

t1 = (1, 2, 3)
t2 = (4, 5, 6)
r = tuple(map(lambda x, y: x + y, l1, l2))
print(r)
This gives the output: (5, 7, 9)
From the above example, we can see that we can also perform operations between two iterables using map. The first element from the first tuple is taken as x and the first element from the second tuple is taken as y. Now, the operation is performed on the x and y and result is stored in-place. Now, same process is followed till the end of tuple. Here, the map object is typecasted into tuple to get the tuple as output.

Filter():

  • The filter is an inbuilt function in Python used to filter out the values from the iterable.

  • For filtering out values, a function is used that returns a boolean value. If the value is true, then that element is kept in an iterable otherwise, it is removed.

  • The syntax of the filter is as follows:

Some examples of filter are as follows:

l = [2, 5, 7, 8, 9]
r = list(filter(lambda x: x % 2 == 0, l))
print(r)
Output will be: [2, 8]
The above code filters out the even numbers of the list. It takes first element from list which is 2 and it is divisible by 2 so the result of the function will be True. so 2 is added in the list. Now, for third element i.e. 5 is not divisible by 2 hence it is not included in the list. Likewise, iterating the whole list it gives the output [2, 8].
l = ("apple", "orange", "watermelon", "kiwi", "mango")
r = tuple(filter(lambda f: len(f) <= 5, l))
print(r)
Output will be: (‘apple’, ‘kiwi’, ‘mango’)
The above code filters out the elements having length not more than 5. Here, the length of the apple, kiwi and mango are less than or equal to 5 hence they are included in the tuple and others are not.

Reduce():

  • Reduce is a function from the functools library. Hence, first we have to import the functools library to use the reduce function.

  • It is used to perform a function on an iterable to obtain a single value at at the end.

  • It takes a number of arguments required in a function and performs the operation. The output of the operation is replaced with the arguments used in the function and then the next iteration is performed using replaced value.

  • The syntax of the reduce is as follows:

  • Some examples of reduce are as follows:

      from functools import reduce
      l = [1, 2, 3, 4, 5]
      r = reduce(lambda x, y: x + y, l)
      print(r)
    
    The output is 17
    The above code calculates the sum of all the elements in the list. Here, first 1 and 2 are taken by function and 3 is given as output. Now in second iteration, 3 and 3 are taken which results into 6, then 6 and 4 which gives 10 and finally 10 and 5 which gives 15. Hence, the next number is added with the previous result of the function.
      from functools import reduce
      l = [2, 3, 8, 9, 5]
      r = reduce(lambda x, y: x if x > y else y, l)
      print(r)
    
    The output is 9
    The above code prints the largest element in the list. In this, first 2 and 3 are taken, so 3 > 2 hence it gives output as 3. Now, 3 and 8 are taken which in turn results into 8 since 8 > 3, then 8 and 9 in which 9 is output. Now 9 and 5 are taken and since 9 > 5, 9 is the final answer of the reduce function.

Thanks for taking the time to read this blog. I think this blog helped you in some way. If so, please consider reviewing and upvoting my blog.

Happy Programming!!!