Sunday, January 23, 2022

How to define and use Anonymous Functions or Lamdas in Python Program

How to create and use of Anonymous Functions or Lamdas in Python Program
In Python, anonymous function means that a function is without a name. In general, we know that def keyword is used to define the general functions.
In the same way, we will use the lambda keyword to define the anonymous functions. 
Syntax:
lambda arguments : expression 

Notes:
Generally the lambdas can have any number of arguments but only one expression, which is evaluated and returned.
The lambda functions can be used wherever function objects are required.

Example 1:
Lets take an example of of creating a function in regular way and using lambdas method.
def cube(k):
    return k*k*k

# calling the function and storing the result into a variable j
j = cube(3)
print('The cube value is :', j)

In above function, we are calculating the cube value of 'i' and while calling the function we are storing the result in to the variable 'j'.

lets re create the above function using the lambdas function.

# defining the lambda function
f = lambda k: k*k*k

# calling the lambda function and storing the result into a variable j
j = f(3)
print('The cube value is :', j)

Here, 'f' is the function name for which the lambda expression is assigned.

# Result:
The cube value is : 27

Example 2:
The lambdas function to calculated the sum of two numbers:

f = lambda x, y:  x + y
result = f(2.35, 4)
print('The sum is: ', result)

# Output:
The sum is:  6.35

Example 3:
The lambdas function to return the biggest of two numbers:

big = lambda x, y: x if x > y else y
a, b = [ int(i) for i in input("Enter two numbers: ").split(',') ]
result = big(a, b)
print('The big number is: ', result)

# Input:
Enter two numbers: 11,17

# Output:
The big number is:  17

# ------------------------------------------------------------------------------------------------------------------------ #

We can pass the lambdas function to another function. The lambda functions are generally used with functions like filter(), map() or reduce().

Lambdas with filter() function:
The filter() function is useful to filter out the elements of a sequence depending on the result of a function. 
Syntax:
filter(function, sequence)
Here, the 'function' represents a function name that may return either True or False; and the 'sequence' represents a list or string or tuple.
When the function returns True, the element will be returned from the sequence otherwise not.

Example:
In the following example we are writing a function is_even() which checks each element of the list and returns only the elements which are even, and store them into a another list.

def is_even(k):
    if k % 2 == 0:
        return True
    else:
        return False
# take a list of numbers
lst1 = [10, 17, 24, 37, 45, 52]
# calling the function
lst2 = list(filter(is_even, lst1))
print('The even numbers are:', lst2)

The above function can rewrite using lambdas in the simple form as shown below:
lst1 = [10, 17, 24, 37, 45, 52]
# calling a lambda function inside the filter() function
lst2 = list(filter(lambda k: (k%2 == 0), lst1))
print('The even numbers are:', lst2)

# Result:
The even numbers are: [10, 24, 52]

# ------------------------------------------------------------------------------------------------------------------------ #

Lambdas with map() function:
The map() is similar to filter() function, but instead of filtering, it will process the each element of a sequence and returns the modified values into a another sequence.
Syntax:
map(function, sequence)
Here, the 'function' represents a function that process the each element of a 'sequence' and returns the modified values into a another sequence. The 'sequence' represents a list or string or tuple.

Example 1:
In the following example we are writing a function squares() which returns the square of each element of the list and returns all the modified elements and store them into a another list.
def squares(k):
    return k*k
# take a list of numbers
lst1 = [1, 0, 3, 2, 1, 3]
lst2 = list(map(squares, lst1))
print('The squares of numbers are:', lst2)

The above function can rewrite using lambdas as shown below:
lst1 = [1, 0, 3, 2, 1, 3]
lst2 = list(map(lambda k: k*k, lst1))
print('The squares of numbers are:', lst2)

# Result:
The squares of numbers are: [1, 0, 9, 4, 1, 9]

Example 2:
# lambda function to map the characters c1 to c2 and vice versa in a string
def replaceChars(str1, c1, c2):
    newChars = map(lambda k: k if (k != c1 and k != c2) else c1 if (k == c2) else c2, str1)

    # join each character without space and print
    print(''.join(newChars))

# passing parameter values to function
if __name__ == "__main__":
    str1 = 'Creative Learning'
    c1 = 'e'
    c2 = 'a'
    replaceChars(str1, c1, c2)

Result:
Craetiva Laerning

# ------------------------------------------------------------------------------------------------------------------------ #

Lambdas with reduce() function:
The reduce() function will process the elements of a sequence according to the function that provided and reduce the sequence to a single value.
The reduce() function can be imported from a Python module 'functools'.
Syntax:
reduce(function, sequence)

Example 1:
from functools import *
# Lambda function with reduce() to return the product of the list of elements
lst = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x*y, lst)
print('The product of the list of values is:', result)

# Output:
The product of the list of values is: 120

Example 2:
from functools import *
# Lambda function with reduce() to return the product of the range of elements
rng = range(1,6)
result = reduce(lambda x, y: x*y, rng)
print('The product of the range of values is:', result)

# Output:
The product of the range of values is: 120

#--------------------------------------------------------------Thanks--------------------------------------------------------------#

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.

Featured Post from this Blog

How to compare Current Snapshot Data with Previous Snapshot in Power BI

How to Dynamically compare two Snapshots Data in Power BI Scenario: Suppose, we have a sample Sales data, which is stored with Monthly Snaps...

Popular Posts from this Blog