Anonymous functions in Python





Hello folks....!!!! 
Today we are going to look how to write anonymous functions.

Anonymous functions :

    These are nothing but functions without explicit names. They are just one line functions mostly. They are defined with the keyword 'lambda'. Theses functions are assigned to a variable and are called using that variable name. The syntax is :

lambda parameters:expression

Consider a function that returns the (number*4). The parameter passed is the number. Look at the code below : 

lambda/anonymous functions

This can be written using lambda functions in a simple manner as given below:

lambda/anonymous function

The keyword lambda is followed by the arguments to be passed, then after a colon(':') the expression to be returned is written. Any kind of expression can be given in the lambda function. Functions like finding square,cube or some mathematical expression can be written. 

Disadvantages of lambda functions

The main advantage of using these lambda functions is a function can be passed as an argument to another function. We all know that there are several built-in functions associated with data structures like lists. One such function is list.sort(). One of the parameters in this function is 'key', based on which the list should be sorted.

Now consider some record like this :
[(87,'rishav', 10), (90,'akash', 5), (3,'ram', 20), (45,'gaurav', 15)] 
We have to sort this based on the second element (name) in each tuple inside the list. Let us look at the code now:

lambda functions in python

We can also generate new iterators based on some conditions.
Now consider two lists:
li1=[45,2,34,1,65,80]
li2=[40,90,33,56,78,30]
Now we need to create a new list which contains the maximum of two elements at each index of the two lists. For example, 
at index '0' - 45>40, so the element 45 from li1 goes into the new list. Now look at the code below :

lambda/anonymous functions in python

In the similar way a list with dictionary can be sorted based on various keys. For example:

lambda/anonymous functions in python

Now the list has been sorted based on the age. Similarly it can be sorted based on the name also.


Next Topic👉

Comments