A lambda function is an anonymous function, which means it is a function without a name.
In Python, a typical function is defined with the def
keyword. The lambda
keyword is used to define an anonymous function.
lambda arguments: expression
A lambda function can take in any number of arguments, but only one expression.
x = lambda y : y + 20print(x(5))
Max = lambda y, z : x if(y > z) else zprint(Max(12, 29))
Find the odd numbers in the list using a lambda function.
# A python code to find odd numbers in a list# using Lambda function# list of numbers from 1 to 11myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]# lambda functionodd_nos = list(filter(lambda a: (a % 2 != 0), myList))print(" Odd numbers in the list : \n", odd_nos)
In the code above, we create a list of numbers (1 to 11).
Next, we use a lambda function to check for odd numbers in the list.
Finally, we extract the odd numbers from mylist[]
and add them to a new list called odd_nos
.
A higher-order function is a function that passes a function as a parameter to another function, meaning it takes a function (or functions) as an argument. It is a first-class function.
The three commonly used higher-order functions are map()
, filter()
, and reduce()
.
map()
functionmap()
is used to apply a given function to each element of an iterable and return an iterable of results in the same order. map()
takes a function and iterable(s) (e.g. list, tuple) as the second argument that is passed sequentially to the function.
map(func, iter)
# map() takes Lambda function as an argumentmyList = [0, 2, 4, 6, 8, 10]newList = list(map(lambda x: (x*5), myList))print("Original list: \n", myList)print ("The new list: \n", newList)
filter()
functionfilter()
is a function that creates an iterable from an old one by matching every element in the new iterable to a predicate that returns a Boolean value. filter()
takes two arguments.
filter(func, iter)
reduce()
functionreduce()
is a function that folds or reduces an iterable into a single value. reduce()
takes two arguments.
reduce(func,iter)
# # reduce() takes Lambda function as an argumentfrom functools import reducea = reduce(lambda x, y: x+y, range(1,51))print("The value of a is ", a)# using reduce to concatenate stringprint(reduce(lambda x, y: x+y, ["Edu", "ca", "tive", " shot"]))