Function - 2

The Anonymous Functions:

These functions are called anonymous because they are not declared in the standard manner by using the def keyword.

Lambda Keyword:

We can use the lambda keyword to create small anonymous functions.

Syntax :-
# lambda [arg1 [,arg2,.....argn]]:expression

Example 1:

# Function definition
sum = lambda arg1, arg2: arg1 + arg2;

# Calling
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))

Value of total : 30

Value of total : 40

The return Statement:

The statement return [expression] exits a function, optionally passing back an expression to the caller.

A return statement with no arguments is the same as return None.

Example 2:

# Function Defination
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2
   print("Inside the function : ", total)
   return total;
# Calling
total = sum( 10, 20 );
print("Outside the function : ", total) 

Inside the function : 30

Outside the function : 30

Example 3:

def cube(y): 
    return y*y*y; 
g = lambda x: x*x*x 
print(g(7)) 
print(cube(5)) 

343

125

Advantage of Lambda Function

  • Without using Lambda :- Here, both of them returns the cube of a given number. But, while using def, we needed to define a function with a name cube and needed to pass a value to it. After execution, we also needed to return the result from where the function was called using the return keyword.

  • Using Lambda :- Lambda definition does not include a “return” statement, it always contains an expression which is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions.

map() function :

  1. The map() function in Python takes in a function and a list as argument.

  2. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item.

Python map() built-in function applies the given function on every item of iterable(s) and returns an iterator object.

Syntax:

map(function, iterable)

fun : It is a function to which map passes each element of given iterable. iter : It is a iterable which is to be mapped.

Returns:

Returns a list,tuple,set of the results after applying the given function to each item of a given iterable (list, tuple etc.)

Note:

The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set)

Example -4:

#!/usr/bin/python3

def square(x):

    return x * x

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

nums_squared = map(square, nums)

for num in nums_squared:

    print(num)

1

4

9

16

25

Python map equivalent function:

The hello() does the same thing as Python 3 map()

Example-5:

def square(b):
    return b*b

def hello(a,b):
    for i in b:
        yield a(i)
    
x = [1,2,3,4,5]
y = hello(square,x)

#print(tuple(y))

for i in y:
    print(i)

1

4

9

16

25

Use of yield instead of return

The yield statement suspends function’s execution and sends a value back to the caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather than computing them at once and sending them back like a list.

Return sends a specified value back to its caller whereas Yield can produce a sequence of values. We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory.

Yield are used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.

def nextSquare(): 
    i = 1; 
  
    # An Infinite loop to generate squares  
    while True: 
        yield i*i                 
        i += 1  # Next execution resumes  
                # from this point      
  
# Driver code to test above generator  
# function 
for num in nextSquare(): 
    if num > 30: 
         break    
    print(num)

1

4

9

16

25

Python map with lambda:

Example-6:

x = [3,5,7]

y = map(lambda x: x*x, x)
print(list(y))

[9, 25, 49]

Python map with multiple iterables:

Example-7:

def multiply(x, y):

    return x * y

nums1 = [1, 2, 3, 4, 5]
nums2 = [6, 7, 8, 9, 10]

mult = map(multiply, nums1, nums2)

for num in mult:
    print(num)

6

14

24

36

50

Python map with multiple functions:

Example-8:

def mul(x):
    return x*x

def add(x):
    return x+x

x=[2,3,5,6]

for i in x:
    y = map(lambda x: x(i),(mul,add))
    print(list(y))

[4, 4]

[9, 6]

[25, 10]

[36, 12]

Python List Comprehension:

Example-9:

def square(x):
    return x*x

x = [1,3,5]

y = [square(i) for i in x]

for j in y:
    print(j)

1

9

25

Problems for practice:

Example-1:

# Python program to demonstrate working 
# of map. 
  
# Return double of n 
def addition(n): 
    return n + n 
  
# We double all numbers using map() 
numbers = (1, 2, 3, 4) 
result = map(addition, numbers) 
print(list(result))

Output:

{2,4,6,8}

Example-2:

def multiply(x):
    return (x*x)
def add(x):
    return (x+x)
funcs = (multiply,add)
for i in range(5):
    value = list(map(lambda x: x(i), funcs))
    print(value)

Output:

[0, 0]

[1, 2]

[4, 4]

[9, 6]

[16, 8]

Example-3:

# map() with lambda()  
# to get double of a list. 
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] 
final_list = list(map(lambda x: x*2 , li)) 
print(final_list)

[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]

Filter() function in python

  1. The filter() function in Python takes in a function and a list as arguments.

  2. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True.

filter() with lambda()

Example 1:

# filter() with lambda() 
x = [2,3,4,5]
y = filter(lambda x: x%2 != 0,x)
print(list(y)) 

[3, 5]

reduce() function in python

  1. The reduce() function in python takes in a function and a list as argument.

  2. The function is called with a lambda function and a list and a new reduced result is returned.

  3. This performs a repetitive operation over the pairs of the list.

  4. This is a part of functools module.

Use of lambda() with reduce()

Example 2:

# reduce() with lambda() 
# to get sum of a list 
from functools import reduce
li = [5, 8, 10, 20, 50, 100] 
sum = reduce((lambda x, y: x + y), li) 
print (sum) 

193

Last updated