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

Learn how to find the intersection of two arrays using Lambda expression and filter() function in Python?
Submitted by IncludeHelp, on March 13, 2022

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]

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]

Python Lambda Function Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.