Lambda(Anonymous) functions in Python, also filter, map and a simple plot

A lambda function in Python is an anonymous procedure(procedure without a name).
Normally functions in Python are declared using the def keyword. If a certain function is required in a very small portion of the program then we are better off with a lambda function.

power = lambda x,y: x**y
print(power(5,4))

This is a simple lambda function to raise x to the power y.
lambda python

Lambda finds special use with the filter function in lists. It is used to choose elements from the list.

l = [1,-2,-3,-4,5,-6,7,8,9,10]
positive = list(filter(lambda x: (x>= 0) , l))
negative = list(filter(lambda x: not(x>= 0) , l))
print(positive)
print(negative)

filter lambda

The map function takes as input a lambda function and creates a new list based on the output.

import math
l = [0,30,45,60,90]
l = list(map(lambda x:math.sin(x*math.pi/180.0) , l))
print(l)

map lambda

 

import math
import matplotlib.pyplot as pp
l=[0,30,45,60,90,120,135,150,180,210,225,
240,270,300,315,330,360]
sinl = list(map(lambda x:math.sin
(x*math.pi/180.0) , l))
print(l,sinl)
pp.plot(l,sinl)

map lambda plot

Leave a Reply