Skip to main content

What is Lambda (Anonymous Function) in Python and How to use it with Filter, Map & Reduce

Anonymous function means that function which does not have a name, so now we can simply say function without having a name is lambda function. To create a normal function in python we need to use the def keyword and while creating the lambda function we need to use the lambda keyword. Hope you have got a brief idea of what is lambda in Python.

Normal Function:

Lambda Function:

Output:

 Output from normal function:  25 
 Output from lambda function:  25 

Here above-defined both function is returning the same thing but using lambda function we will be removing the uses of keywords like def, return and also we are reducing the number of lines, You can use any number of argument as you want but the expression should be only one. 
Lambda function does not require a return statement because it returns the expression itself directly. Where ever you need one expression with any number of arguments you can use the lambda function without even assigning the variable at all.

Use Lambda with Filter, Map & Reduce

Filter:

It is an inbuilt function in python, As the name suggests it takes the input (Iterable data) and returns the filtered data. Whenever you have a list or any other iterable and you want filtered data from that you can use the filter function it would be the best choice.

 filter(function, list) 

Now here you can see filter function takes two argument - list and function, List is your data that you want to filter, and function where you will define your operations. Here in the place of the function argument, we are going to use the lambda function. Now let's see in below code.

Using Filter with Lambda:

Output:

 Even numbers: [6, 12, 18] 

Explanation:

In the above example code, list_data is the list of any random integer and then I am passing it the to filter function. Now I have created the lambda function that will take list data one by one and match with our condition (even % 2 == 0) if the condition becomes is true then it will put the returned value inside a new list. And finally, we are printing the list i.e. even_num.

Map

It is an inbuilt function in python, It takes the input (Iterable data) and performs some operation as you define and returns final data. So if you want to perform some operation on all the elements of a list or any other iterable data you can use the map function.

 map(function, list) 

Now here you can see map function takes two arguments - list and function, List is your data that you want to perform some operation on it and function where you will define your operations. Here in the place of the function argument, we are going to use the lambda function. Now let's see in below code.

Using Map with Lambda:

Output:

 Double numbers: [6, 10, 18, 12, 26, 24, 36, 14] 

Explanation:

In the above example code, list_data is the list of any random integer and then I am passing it the to map function. Now I have created the lambda function that will take list data one by one and perform the operation (i.e. multiplying by 2) to each element of a list and then it will return the final list with having all the elements multiplied by 2.

Reduce

As the name suggests it will reduce your list to a single value. So if you have a chuck of value and you want to add all the values or multiply all the values you can choose this cool function to handle that for you.

 reduce(function, list) 

Now here you can see filter function takes two argument - list and function, List is your data that you want to reduce it into a single value and function where you will define your operations. Here in the place of the function argument, we are going to use the lambda function. 
Now here let me tell you one thing otherwise you will get an error while executing this code, reduce is not an inbuilt function it belongs to a module name as functools. Now from this module you can import reduce now let's see the example.

Using Reduce with Lambda:

Output:

 Addition result: 73 

Explanation:

In the above example code, list_data is the list of any random integer and then I am passing it the to map function. Now I have created the lambda function that will take list data and add all the elements one by one and then returns one single final value. 
If you see in this code you will not find a list while creating a reduce because reduce only returns a single value.


Thank you for visiting my blog๐Ÿ˜Š! If you enjoyed this article, you can subscribe to my blog for the latest updates. Let me know your comments about this article.

Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Here are the sports toto: NFL, NBA, NHL, NHL, NCAAB, NDS
    FanDuel Sportsbook & Casino ์•ˆ์‚ฐ ์ถœ์žฅ์ƒต is offering sports betting, premier promotions, and a ๋™ํ•ด ์ถœ์žฅ์ƒต great sign up ํ† ํ†  ์‚ฌ์ดํŠธ ์ฝ”๋“œ bonus. New users can use FanDuel Points and Promo ๊ฐ•์›๋„ ์ถœ์žฅ๋งˆ์‚ฌ์ง€ Code ๊ฒฝ์ฃผ ์ถœ์žฅ์ƒต

    ReplyDelete

Post a Comment

Popular posts from this blog

What is Cryptography and the Process of Encryption/Decryption with Python (AES - CBC Mode)

In the IT industry, Cryptography is one of the most important techniques to secure sensitive data. According to Wikipedia Cryptography is about constructing and analyzing protocols that prevent third parties or the public from reading private messages. What this exactly means let's understand, now assume that you have a secret message that you do not want to share with any other except the receiver. Of course, you are sending the message to the receiver so he only will receive that message but what if someone manages to hack your message. In this case, if your message will be in a normal text he can easily read it, so to avoid this type of risk we encrypt our message before sending it. So that even if someone manages to hack our message he can not read the message. As per my understanding, the Encryption/Decryption or Encoding/Decoding of the message is called Cryptography. There are multiple ways to Encrypt and Decrypt the message, I will be covering here AES (Advanced Encryption...

How to Create a REST API with Python and FastAPI Framework

Welcome! Let's take a look at "How to create a REST API with Python and FastAPI framework"๐Ÿš€. API is essential for building a multi-layer application structure, so choosing the right framework for your API can make the performance of your application robust. FastAPI is a modern, fast (high-performance), a web framework for building APIs with Python 3.6+ based on standard Python type hints ( source ). It is written in Python with Starlette and Pydantic as a base. Big bull companies like Microsoft, Uber, Netflix, etc. have already started using FastAPI. One of the reasons why I like FastAPI is because of the automatic interactive documentation. It will auto-generate Swagger documentation (not only Swagger but also Redoc) for you without any trouble of writing additional code. Let's Begin Coding... Prerequisites: Python 3.6+ (and how to use it๐Ÿ˜‚) pip (if already installed then ignore) Install FastAPI from pypi using pip, you also need to install an ASGI server.  pip inst...