Lambda functions in python

Traditionally, most programmers use functions and macros to write re-usable routines. In Python there is a simple way write quick one liner functions which can be used throughout your program.

Lambda functions are also known as anonymous functions. Syntax of lambda function is like:


Name_of_function = lambda arg1, arg2...argn : Operation/Condition check

Here are few examples.


# Add 2 to a number
lamb1 = lambda x : x+2

# Multiply two numbers
lamb2 = lambda a,b : a*b

# Check if a number of Odd or Even
lamb3 = lambda x: print("Even number") if x % 2 == 0 else print("Odd number")

A few more practical use cases to write geometry functions which may be required repeatedly in program.


#!/usr/bin/python3
import math

# A few lamba functions to calculate area and perimeter of common geometric figures
t_peri = lambda p,q,r : p + q + r
r_area = lambda len, ht : len*ht
c_peri = lambda rad : 2*math.pi*rad
c_area = lambda rad : math.pi*rad*rad

# invoke functions and print results.
print("Perimeter of Triangle (10,20,15) is:", t_peri(10,20,15))
print("Area of Rectangle (30,20) is:", r_area(30,20))
print("Perimter of circle (5) is:", c_peri(5))
print("Area of circle (15) is:", c_area(15))

Output:


./lambdatests.py
Perimeter of Triangle (10,20,15) is: 45
Area of Rectangle (30,20) is: 600
Perimter of circle (5) is: 31.41592653589793
Area of circle (15) is: 706.8583470577034