Python uses sets to find the intersection of two lists

Document 对象参考手册Python3 Examples

In Python, a set is an unordered data structure with no duplicate elements. We can use the properties of sets to find the intersection of two lists. The intersection refers to the elements that exist in both lists.

Example

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

# Convert the lists to sets
set1 = set(list1)
set2 = set(list2)

# Use the set intersection operation
intersection = set1 & set2

# Convert the result back to a list
result = list(intersection)

print(result)

Code analysis:

  1. list1andlist2These are two lists containing integers.
  2. set(list1)andset(list2)Convert the lists to sets, which removes duplicate elements and facilitates set operations.
  3. set1 & set2Use the set intersection operator&to find the elements that exist in both sets.
  4. list(intersection)Convert the result back to list form for output.
  5. print(result)Output the final intersection result.

Output result:

[4, 5]

Document 对象参考手册Python3 Examples

Other extensions