春江暮客

春江暮客的个人学习分享网站

Finding Common Values in Two Python Lists

2019-03-08 Technology
Finding Common Values in Two Python Lists

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.

In practice, the important differences are not only whether the code works, but also whether the result removes duplicates and whether it preserves the original list order.


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}

This is the shortest version, but the result is a set, so duplicates are removed and the original list order is not preserved.

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}

This is essentially the same idea as the previous method: it returns a set intersection, so it is also unordered and deduplicated.

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]

If you want the result to keep the order from list1, this list-comprehension form is often the clearest choice.

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}

This also produces the intersection, but it is usually less readable than the first two set-based approaches.

Which Method Should You Use?

  • If you only care about the shared values and do not care about order or duplicates, use set(list1) & set(list2).
  • If you want to preserve the order from list1, use the list comprehension.
  • If the lists are large and you still want ordered output, a practical hybrid is to convert the second list to a set first.
set2 = set(list2)
[element for element in list1 if element in set2]

友情链接

其它