In daily life, we often encounter the need to find common values between two arrays. This article provides several simple and practical methods on how to elegantly get common values between two arrays in Python.
1. Using the &
operator with sets
list1 = [1,2,3,4,5,6,7]
list2 = [1,3, 5, 7, 9]
set(list1) & set(list2)
#{1, 3, 5, 7}
2. Using the intersection()
method with sets
list1 = [1,2,3,4,5,6,7]
list2 = [1,3, 5, 7, 9]
set(list1).intersection(list2)
#{1, 3, 5, 7}
3. Brute-force checking if an element from the first list is in the second list
list1 = [1,2,3,4,5,6,7]
list2 = [1,3, 5, 7, 9]
[element for element in list1 if element in list2]
# [1, 3, 5, 7]
4. Using set subtraction
list1 = [1,2,3,4,5,6,7]
list2 = [1,3, 5, 7, 9]
set(list1) - (set(list1)-set(list2))
#{1, 3, 5, 7}