Lambda Functions in Python -II

HINA SAYYAD
3 min readFeb 5, 2022

Today’s Agenda :

  1. General use of lambda functions
  2. filter()
  3. reduce()
  4. map()

General use of lambda functions :

1. filter() : The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.

To each element in the list lst, fun function is applied and checks if the result is true or false. All the true resulted elements are collected in a new list evn_lst and displayed. In the output we can see that evn_lst is a filter object, to get the list we have to type cast it to list. And the new output displays the filtered list evn_lst.Let us now see how the code changes when we use lambda function.

2. reduce( ) :The reduce() function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. This function is defined in “functools” module.

In the above diagram we are trying to reduce the list lst by adding all the elements and storing the result in res.

Let us see how to use reduce() with normal def function before comparing with lambda function.

Using def function we had to write the logic in 4 lines let us see how the code changes with the use of lambda function.

3.map( ): map() function returns a map object of the results after applying the given function to each item of a given sequence (list, tuple etc.) For example let’s take a list with certain numbers and map it with its squared values. Syntax : map (function,sequence).

Let us try to code the above logic using def function first and then use lambda function.

Let us see the same code with lambda function now.

THANK YOU FOR READING :)

--

--

HINA SAYYAD

A vibrant mind with great personality.Always opine enigmatic thought about everything. Like to write about technology and lifestyle.