Q:

Intersection of two arrays using Lambda expression and filter() function in Python

belongs to collection: Python Lambda Function Programs

0

Given two arrays (array1 and array2), we have to find their intersection.

Example:

Input: 
array1[] = [11, 10, 22, 20, 35, 67]
array2[] = [22, 30, 35, 11]

Output:
Intersection: [22, 35, 11]

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Python code to find intersection of two arrays using Lambda expression and filter() function

In the below code, to find the intersection of two arrays – we are using lambda expression and filter() function.

The filter() function is a built-in function that is used to filter the given sequence (sets, lists, tuples, etc.) with the help of a function that checks each element in the given sequence to be true or not. And, the lambda function is an anonymous function - that means the function which does not have any name.

# Function: ArrayIntersection
# the function will accept two arrays
# and, will find the intersection

def ArrayIntersection(a1, a2):
     # Here, the lambda expression will filter
     # the element e list a2 where e
     # also exists in a1
     result = list(filter(lambda x: x in a1, a2)) 
     print ("Intersection : ",result)
  
# Main function
if __name__ == "__main__":
    # Two arrays 
    array1 = [11, 10, 22, 20, 35, 67]
    array2 = [22, 30, 35, 11]
    
    # function call to find intersection
    ArrayIntersection(array1, array2)

Output:

Intersection :  [22, 35, 11]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Find small number between two numbers using Lambda... >>
<< Map() Function and Lambda Expression in Python to ...