Lambda Keyword In Python

Overview:

  • The lambda keyword in Python is used for writing lambda expressions.
  • These lambda expressions define small anonymous functions. The anonymous functions do not have a name.
  • Lambdas are useful, when the developer intends to write a function which is not going to be useful as a regular function to call from other parts of the program.
  • The developer may want something crisp, yet a function without a name and select lambda expression for that.
  • The advanced use of the lambda keyword is when the developer wants to define a function as in functional programming…not the simple one as stated above but a function, which is decomposed into so many unit functions…the pure ones without any side effects.
  • This article will restrict itself in explaining the lambda keyword using crisp lambda expressions without describing about the functional calculus, functional programming vs imperative programming, side effects of regular functions and how program invariants are distributed in so many places of the program when using the regular function defined using the def keyword as apposed to a fairly complex lambda expression consisting of pure lambda functions.

 

Defining a function in Python using the lambda keyword:

  • An anonymous function or lambda function is defined using the lambda keyword followed by the arguments separated by commas followed by a colon: followed by an expression making use of the arguments.
  • The expression followed by: cannot use any Python statements. However it can use other functions in a nested way. The more nested it is, the less it is easily understood but a pure functional program can be written this way.

Example:

# Example python program using a lambda expression

circleArea = lambda r, pi: pi*r*r;

 

# No use of radius = 10 and pi = 3.14...don't want to be imperative...pure functional

a1 = circleArea(10, 3.14);

print("Area of the circle");

print(a1);

 

Output:

Area of the circle

314.0

 

 


Copyright 2020 © pythontic.com