Python Use a Set to Find the Union 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 union of two lists. The union refers to the set of all elements in both lists, with each element appearing only once.
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 union operation
union_set
=
set1.
union
(
set2
)
Convert the result back to a list
union_list
=
list
(
union_set
)
(
union_list
)
Code analysis:
list1andlist2are two lists containing duplicate elements.set(list1)andset(list2)Convert the lists to sets, automatically removing duplicate elements.set1.union(set2)Use the set'sunionmethod to find the union of the two sets.list(union_set)Convert the union set back to list form.- Finally, print the union list.
Output result:
[1, 2, 3, 4, 5, 6, 7, 8]
Python3 Examples