Lambda, Filter, and Map functions in Python

Published

October 4, 2019

Lambda

Lambda is an important function/operator to create anonymous in-line functions in pyhton.

Basic syntax:

lamda arguments: expression

#This is our usual function where we have to define a name for the function
def func(x,y):
    return(x+y)
func(2,3)
5
#Lambda function 
add=lambda x,y:x+y
add(2,3)
5

lambda functions can be used in place of a iterator when sorting – this allows for selecting the column or the varible according to which sorting has to be done

import numpy as np 
np.random.seed(42)
a1=np.random.choice(10,5,replace=False)
file_list=[]
for i in a1: 
    file_list.append('{0}-{1}'.format('Filename',i))
print(file_list)
['Filename-8', 'Filename-1', 'Filename-5', 'Filename-0', 'Filename-7']
file_list=sorted(file_list, key=lambda x:x.split('-')[-1])
file_list
['Filename-0', 'Filename-1', 'Filename-5', 'Filename-7', 'Filename-8']

Map

When you want to have multiple outputs for the functions but do not want to write a for all explicitly you can use map function for pseeding things up

def square(x):
    return(x**2)

print(a1)
ans=[square(i) for i in a1]
print(ans)
[8 1 5 0 7]
[64, 1, 25, 0, 49]
#Using map function
map(square,a1)
<map at 0x7f85058e5eb8>
#You'd have to first converrt it to list 
list(map(square,a1))
[64, 1, 25, 0, 49]

Combining the two:

a=np.random.choice(10,5,replace=False)
b=np.random.choice(50,5,replace=False)
result=map(lambda x,y:x*y,a,b)
print(a)
print(b)
print(np.asarray(list(result)))
[0 1 8 5 3]
[36 16  4  9 45]
[  0  16  32  45 135]