Thursday, 15 December 2016

Python 'lambda' or Anonymous Functions

Python lambda or anonymous function - We are still learning Python functions and the discussion would be incomplete unless there is a mention about Python 'anonymous' functions. We have already studied in one of our previous articles, on Function definition, about the def construct. We define a function with def followed by the function name and the parameters, if any. With this, Python creates an object of type function, which can be used later with the name assigned to it. Besides this, Python lets us creates functions, which can be called later, but are not bound or assigned to a name – hence called as ’Anonymous’ or Unnamed functions. How to create them?, we learn in this article.

Just like def, in Python, we have another construct lambda that returns a function type without assigning a name to it. This return value (a function) can be assigned a name later. As they produce a value, they are considered as Expressions, not Statements. (Expressions produce a value, while statements perform some task. But, one must remember that, expression is [or a part of] statement.) Moreover, where normal function may consist of a block of statements, lambda functions contains only one expression. This is because, lambdas are intended to create simple functions. To perform heavier tasks, one should definitely create functions using def. While lambda, like normal function, can have any number of parameters in the definition. Lets take a look at lambda’s syntax.

Note: lambda can have only one expression, but any number of parameters in its definition. It is an expression, not a statement


lambda param1, param2, ..., paramN : expression 

Using lambda Functions

Even though there are a few dissimilarities between normal functions and anonymous ones, they being of the same type function, do the same tasks for us. Let us write a function to obtain square of a number.

>>> def square(num):
...     return num ** 2

>>> print square(11)
>>> print square(13)

Let’s achieve the same thing using a lambda function. Remember, lambda do not have return statements, they have expression, mind that singular form. In this case, we create a lambda function and assign the return value (which is a function type) to a name, say sqr.

>>> sqr = lambda num : num ** 2

>>> type(sqr)
<type 'function'>
>>> sqr(11)
>>> sqr(13)

Arguments to lambda function work same as that in case of normal functions. We can have keyword arguments, defaults and optional arguments in case of lambdas. Let’s check with the keyword arguments first.

# lambda function to calculate 'n' power of a number
>>> power = lambda base, exponent : base ** exponent

# 10 ** 2 = 100
>>> print power(10, 2)

# This becomes 2 ** 10 = 1024
>>> print power(exponent=10, base=2)

And, now the defaults.

# lambda function to welcome a user, with default value
>>> welcome = lambda user="Whosoever you are" : 'Welcome, ' + user + ' !!'

# This will take the default value and a rude welcome
>>> welcome()
'Welcome, Whosoever you are !!'

# This will override the default value
>>> welcome('Mandar')
'Welcome, Mandar !!'

We can also use lambdas in lists and dictionaries in order to choose between several actions to be performed. Take a look at below example, in which we have used a dictionary with action name as key and lambda function as its value. When you access a key, it will be a function, while if you provide it with argument(s), you will get appropriate result.

>>> functions = {'power' : lambda x, y: x**y, 'tenTimes' : lambda x : 10 * x, 'sqrt' : lambda x : x ** 0.5 }

>>> type(functions['tenTimes'])
<type 'function'>

>>> functions['power'](10, 2)

>>> functions['tenTimes'](20)

>>> functions['sqrt'](224)

Let us now see how we can use lists in the similar context.

>>> funcList = [ lambda x, y: x**y, lambda x : 10 * x, lambda x : x ** 0.5 ]

>>> type(funcList[1])
<type 'function'>

# Power
>>> funcList[0](6, 3)

# 'tenTimes'
>>> funcList[1](12)

# 'sqrt'
>>> funcList[2](124)

So, we have come to an end of the scope of this article. This article was intended to provide a primer on lambdas. The scope for the lambdas to be used is very vast. In the upcoming articles, we would be learning about some important functions often useful in functional programming, which would also be using lambda functions. Kindly post your views in the comment section below and stay tuned. Thank you.


Post a Comment