Pages

Sunday, December 30, 2018

Python Lambda Functions - Quick Notes

Lambda functions:

  • are anonymous functions with no function name but with function body or definition
  • are useful when a small function is expected to be called once or just a few times
  • are useful as arguments to a higher-order function that takes other functions as arguments
    • For example, to filter out some data from a list based on some condition, using a lambda function might be concise and simpler than writing a full-fledged function to accomplish the same task.
  • are defined using the lambda keyword in Python
  • can accept any number of arguments (zero or more)
  • can have only one expression that gets evaluated and returned

Syntax:

 lambda argument(s): expression

eg.,

A trivial example.

def areaofcircle(radius):
 return math.pi * radius * radius

can be written as:

circlearea = lambda radius : math.pi * radius * radius

In this example, the lambda function accepts a lone argument radius; and the function evaluates the lambda expression (π * radius2) to calculate the area of a circle and returns the result to caller.

In case of lambda function, the identifier "circlearea" is assigned the function object the lambda expression creates so circlearea can be called like any normal function. eg., circlearea(5)

Another trivial example that converts first character in each word in a list to uppercase character.

>> fullname = ["john doe", "richard roe", "janie q"]
>>> fullname
['john doe', 'richard roe', 'janie q']
>>> map(lambda name : name.title(), fullname)
['John Doe', 'Richard Roe', 'Janie Q']

No comments:

Post a Comment