Python @ DjangoSpin

Python: Lambda Expressions (Anonymous functions)

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Lambda Expressions in Python

Lambda Expressions in Python

Lambda expressions(a.k.a. lambda forms) in Python are used to create anonymous functions. In a nutshell, these functions do not have the def keyword, instead have a lambda keyword, take any number of arguments and return a single value in the form of an expression.

# Syntax of a lambda expression:
lambda [arg1 [,arg2,.....argn]]:expression
 
# Example
>>> myLambdaExpr = lambda x: x + 2
>>> myLambdaExpr(5)
7
 
>>> myLambdaExpr
<function <lambda> at 0x02D21978>
 
>>> def myNormalFunc():
    print()
     
>>> myNormalFunc
<function myNormalFunc at 0x02D219C0>
 
# Example
>>> add = lambda num1, num2: num1 + num2
>>> add(3,4)
7

Lambda expressions may not necessarily enhance readability, but they help in making the code compact, as they replace elementary functions which return a single expression.

In actuality, lambda is the basic form of a function definition. Any function, in principle, is a lambda assigned to a variable. The expression "lambda arguments: expression" yields a function object. The unnamed object behaves like a function object defined with

def (arguments):
return expression

Keep in mind that:

  • Lambda expressions cannot contain statements.
  • Lambda expressions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
  • Lambda expression are extremely useful in GUI Programming. They serve as callback functions.
  • In a broad sense, anything you can do with a lambdas, you can achieve the same with named functions, or lists. However, it’s up to you to choose whether to use lambdas or not. You could decide based on the readability of your code.
  • l = lambda x: x + 2 is the same as def l(x): return x + 2

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply