Intersection of two Arrays in Python ( Lambda expression and filter function )
Last Updated :
20 Jan, 2025
Improve
Finding the intersection of two arrays using a lambda expression and the filter() function means filtering elements from one array that exist in the other. The lambda defines the condition (x in array2), and filter() applies it to the first array to extract common elements.
For example, consider two arrays, a=[1,3,3,5,5,7] and b=[2,3,5,6]. The goal is to find the intersection of these two arrays i.e., the elements common to both arrays. The result of this operation would be [3, 5]
, as these are the elements present in both arrays.
a = [1, 3, 4, 5, 7]
b = [2, 3, 5, 6]
# Use filter with lambda to find common elements
res = list(filter(lambda x: x in a, b))
print(res)
Output
[3, 5]
Explanation:
- lambda function: This function takes an element
x
and checks if it exists in arraya
and
It returnsTrue
if the elementx
is present ina
, otherwise it returnsFalse
. filter(lambda x: x in a, b)
:This function applies the lambda function to each element of arrayb
.list()
:This convert filter object is converted into a list .- print(res): This prints the resulting list, which contains the intersection of arrays a and b.