Lambda Function in Python Examples-DecodingDevOps

Lambda Function in Python Examples

Lambda function is a single inline function that is defined without any name and this function can have any number of arguments but it has only one expression. This function behaves similar to the normal function which is declared using the def keyword. This function can be used whenever the function objects are required. This function does not need a return statement as it always returns a single expression. This function also takes the multiple arguments in this aspect.

SYNTAX:  lambda arguments : expression

sum = lambda a : a + a       # adds two a in a single expression
print(sum(20))                #prints output 40 

# multiple arguments
sum = lamda a, b, c: a+b+c
print(sum(10,20,30))


# normal function
def add(a,b,c):
    return a+b+c
result = add(10, 10, 10)
print(result)

OUTPUT:
40
60
30

1.MAP FUNCTION-  The map() function is used to apply an operator or expression to every element in the sequence. This function will take two items as an input, an object, and a sequence. it is used to apply a function on all the elements of the specified iterable and return a map object. The returned value from the map can be passed to list(), set() in this aspect.

MAP FUNCTION SYNTAX:  map(function, iterable)

Examples for Map Function:

numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result)

# passing multiple iterators
num1 = [4, 5, 6]
num2 = [5, 6, 7]

result = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result))

OUTPUT:

{16, 1, 4, 9}
[9, 11, 13]

2.FILTER FUNCTION:  it is a built-in function in python which is used to filter an iterable element This method filters the given iterable with the help of a function that tests each element in the iterable to be true or not. it filters the item out of a sequence. The iterable element can be any container that supports iteration or an iterator.

SYNTAX FOR FILTER FUNCTION:  filter(function, iterable)

EXAMPLE:

a = range(1,11)
print (list(filter(lambda x:x%2==0,a)))

# normal function
a = range(1,11)

def even(n):
    if n%2==0:
        return True
    return False

print (list(filter(even,a)))

OUTPUT:
[2,4,6,8,10]
[2,4,6,8,10]

3.REDUCE FUNCTION:  this method is used to apply a function to each element in the array to reduce the array to a single value. the return value of the function is stored in an accumulator. The argument function is applied cumulatively to arguments in the list from left to right. The result of the function in the first call becomes the first argument and the third item in list becomes second. This is repeated until the list is exhausted.

SYNTAX:  reduce(function, iterable)

EXAMPLES:

product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
print(product)

# normal function
product = 1
list = [1, 2, 3, 4]
for num in list:
    product = product * num

OUTPUT:
24
24

Leave a Reply

Your email address will not be published. Required fields are marked *