Python uses sets to find the intersection of two lists
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)
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:
list1andlist2These are two lists containing integers.set(list1)andset(list2)Convert the lists to sets, which removes duplicate elements and facilitates set operations.set1 & set2Use the set intersection operator&to find the elements that exist in both sets.list(intersection)Convert the result back to list form for output.print(result)Output the final intersection result.
Output result:
[4, 5]Other extensions
Python3 Examples