Python lambdas

Lambdas or anonymous functions, is not new with functional programming languages. I do understand that for beginners and programmers not having experience with functional languages will find it a bit hard to understand it at the beginning, but I am here to help to make it more comprehensible.

Let us take an example,

Suppose we need a function which returns the sum of two arguments, how will be achieve it in normal function notation,

def add(x,y):

return x+y

# Now the same in lambda:

add = lambda x,y : x + y

add(1,2)

3 # output

# that is it, now we have a function add(x,y) which returns sum of x+y

# Let us create a lambda function to get square root of a number

sqrt = lambda n : n ** 2

sqrt(2)

# output

4

Isn’t it great?

You can of course use one off functions to achieve the same results, but there could be situations where using lambdas could prove beneficial, specially in “callbacks” to GUI frameworks such as Tkinter and wxPython.

Some pointers for lambdas in Python:

  • Lambdas can take only a single expression. Expression are combinations of values and operators which evaluates and always evaluates down to a single value. And a statement is every other instruction. In python expressions could be statements sometimes.

PS: In Python assignment statements do not return anything. ex; a = b = 0 in Python means chained assignment statement but it does not return any value as in C language.

So, it is safe to say that if nothing is returned then it cannot be put in lambda, or if it is not an expression then it cannot be put into lambda.

  • Function calls are expressions and could be used in lambdas.
  • You can also use closure function in lambdas and you can of course pass function as arguments or arguments to functions inside lambdas.

add = lambda x: lambda y : x + y

# to call add

add(1)(2)

# gives output

3

  • Since Python 3 print has become a function, so it could be used in lambda even though it returns None, but just because it is a function, it could be used.
  • Lambdas are late addition to Python, that is the reason why it generally does have some restrictions to even normal operations in Python.
  • Return statement is implicit in lambda, so, the thing to remember is that lambdas in Python always returns something from the expression evaluated inside lambdas, but their wont be any explicit return statement.

 

I believe that Python lambdas has lot of potential is used carefully. Hope this tutorial helps in understanding it a bit.

 

Leave a Reply

Your email address will not be published. Required fields are marked *