The intersection of two arrays in Python (Lambda expression and filter function )

In this article, we will learn about finding the intersection of two arrays in Python using lambda expressions and the filter function. The intersection contains elements that are common to both arrays.

The problem is that we are given two arrays and we need to find the common elements between them using functional programming concepts.

Algorithm

Here's the step-by-step approach ?

  1. Declare an intersection function with two array parameters
  2. Use a lambda expression with the filter function to select elements from the second array that exist in the first array
  3. Convert the filtered result to a list using typecasting
  4. Display the intersection result

Example

Let's implement the intersection function using lambda and filter ?

def interSection(arr1, arr2):
    # using filter method to find identical values via lambda function
    values = list(filter(lambda x: x in arr1, arr2))
    print("Intersection of arr1 & arr2 is:", values)

# Driver program
if __name__ == "__main__":
    arr1 = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
    arr2 = ['p', 'o', 'i', 'n', 't']
    interSection(arr1, arr2)

The output of the above code is ?

Intersection of arr1 & arr2 is: ['o', 'i', 't']

How It Works

The filter() function applies the lambda expression lambda x: x in arr1 to each element in arr2. The lambda checks if each element from arr2 exists in arr1, returning only the common elements.

Alternative Approach with Set Intersection

For comparison, here's a more efficient approach using sets ?

def interSection_set(arr1, arr2):
    # Convert to sets and find intersection
    intersection = list(set(arr1) & set(arr2))
    print("Intersection using sets:", intersection)

# Example usage
arr1 = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
arr2 = ['p', 'o', 'i', 'n', 't']
interSection_set(arr1, arr2)
Intersection using sets: ['i', 'o', 't']

Comparison

Method Time Complexity Maintains Order? Handles Duplicates
Lambda + Filter O(n*m) Yes Preserves from second array
Set Intersection O(n+m) No Removes duplicates

Conclusion

The lambda and filter approach provides a functional programming solution for finding array intersections while preserving element order. For better performance with large datasets, consider using set intersection instead.

Updated on: 2026-03-25T06:07:26+05:30

779 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements