The purpose of this blog is to happily share my learning and ideas to help people, who actively seek solutions for the day-to-day problems faced.

Recent Posts

Python: lambda or anonymous funtion - Explained

It's not who I am underneath but what I do that defines me - Batman (Let me make use of some herioc quotes, at least that's what you expect from a fan of Christoper Nolan)

Batman and Lambda


Ha Ha.. enough of the drama. The above quote just not only suits for Batman but also for Python's anonymous function called lambda 

Though this saviour is not going to play a major role in saving some real life but it does save few lines of our python code and so is our time, so why not learn about it

Unlike some usual python funtions, lambda doesn't need any 'def' keyword to define it as a function, it can defined with the 'lambda' keyword as shown below

lambda arguments : expression

But the point to remember here is it can take any number of arguments but can have only one expression to evaluate and return the result

Hey wait bro, but I can do the same with a normal function right ? (of course with few additional lines) so what's a big deal about lambda 

Use case:

We can create simple lambda functions and also we can define it inside another functions (the place where it true powers comes in)

Examples:

1. Simple Lambda function

In [1]: x = lambda a, b, c : a + b + c
In [2]: print(x(5, 6, 2))
13
In [3]:

2. Lamda defined inside another funtion

Consider we have a function that takes only single argument and do some calculations with some unknown argument as shown below

In [3]: def myfunc(n):
   ...:       return lambda a : a * n
   ...:
In [4]: mydoubler = myfunc(2)
In [5]: print(mydoubler(11))
22
In [6]:

Ok now let's check a tripler with the same function as shown below

In [6]: mytripler = myfunc(3)
In [7]: print(mytripler(11))
33
In [8]:

So the final take is we can make use of lambda funtion to do some calculations for a short interval (Ah ! then you're no where near to my super hero Batman, ahem ahem.. the comparison was only made to grab your attention :P)

2 comments:

  1. It was so funny how you are explaining the concepts..but you are explaining it in a clear way

    ReplyDelete
  2. Ha ha.. I love some humour with learning, thanks for checking out the post

    ReplyDelete