Tuesday, February 8, 2022

Lambda functions

Lambda functions are Python’s anonymous functions, that is, they are defined without a name. These functions are defined using lambda keyword instead of def. The syntax for lambda function is as follows:

lambda arguments: expression

The most interesting feature about lambda functions is that it can have any number of arguments but only one expression. The expression is evaluated, and the value is returned. Ideally, lambda functions are used if there is a requirement of function objects.

For example:

your_age = lambda yr_of_birth: 2021 - yr_of_birth

print(your_age(1956))

Output:

65

Three functions map(), filter(), and reduce()were created to facilitate functional approach in Python programming. In Python 3 reduce() has been discontinued. These functions can be replaced by List Comprehensions or loops. The following example demonstrate how to use lambda function with filter().

number = [1,2,3,4,5,6,13,7,8,9,0]

odd_number = list(filter(lambda x : (x%2!=0), number))

print(odd_number)

The above example use lambda function with filter() to print odd numbers from a given list. Similarly, map() function applies the same function to each element of a sequence and returns a modified list.

Suppose we need to square every number in list [1,2,3,4,5], the usual way of doing this would be:

list1 = [1,2,3,4,5]

for element in list1:

print(element**2)

We can use map() along with lambda to produce the same result:

print(list(map(lambda x: x**2,list1)))

Try some more examples by rewriting the normal codes using lambda functions, for example the following code -

def addFunc(a,b):

return a+b

print(addFunc(5,2))

Try to rewrite this using lambda function. Answer will be provided in the next post.

Share:

0 comments:

Post a Comment