In [1]:
def doubler(input_number):
return input_number*2
In [2]:
doubler(45)
Out[2]:
In [3]:
temp_fn = lambda arg : arg*2
In [4]:
temp_fn(55)
Out[4]:
In [5]:
type(temp_fn)
Out[5]:
It looks silly now, but lambdas work great with map
and other productivity functions. You can have other methods and functions that do the heavy lifting and call them in a particular order from a lambda
The map
function will perform an operation on all elements of an input list. You can execute a function on all elements of a list without a loop, like a comprehension.
map(function, sequence) --> applies the function for each element in the sequence. The return sequence if of same length as input sequence
In [6]:
l1 = [1,2,3,4,5,6,7]
#to double elements in this list using list comp
l1_double = [i*2 for i in l1]
l1_double
Out[6]:
In [7]:
#double using map and a function
l1_double_2 = list(map(doubler, l1))
l1_double_2
Out[7]:
In [15]:
#double using map and a lambda function
l1_double_3 = list(map(lambda arg:arg*2, l1))
l1_double_3
Out[15]:
filter
function is used to filter out elements in a sequence based on a condition
filter(function, sequence) --> applies the function for each element in sequence, but the return sequence is same or smaller than input based on the condition in the `function`.
The function should return a bool
In [9]:
#find only the odd numbers --> list comp way
l1_odd = [i for i in l1 if i%2 > 0]
l1_odd
Out[9]:
In [13]:
# find only odd numbers --> filter with lambda way
l1_odd_2 = list(filter(lambda arg:arg%2>0, l1))
l1_odd_2
Out[13]:
In [ ]: