Python Use a Set to Find the Intersection of Two Lists
In Python, a set is an unordered and non-repeating data structure. We can use the characteristics 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 list to a set
set1
=
set
(
list1
)
set2
=
set
(
list2
)
Use the set intersection operation
intersection
=
set1 &
;
set2
Convert the result back to a list
result
=
list
(
intersection
)
(
result
)
Code analysis:
list1andlist2are two lists containing integers.set(list1)andset(list2)Convert the list to a set, which removes duplicate elements and facilitates set operations.set1 & set2Use the set intersection operator&to find 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]
Python3 Examples