Python Using Sets 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 from both lists, and each element appears only once.
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 union operation of sets
union_set = set1.union(set2)
# Convert the result back to a list
union_list = list(union_set)
print(union_list)
list2 = [4, 5, 6, 7, 8]
# Convert the lists to sets
set1 = set(list1)
set2 = set(list2)
# Use the union operation of sets
union_set = set1.union(set2)
# Convert the result back to a list
union_list = list(union_set)
print(union_list)
Code explanation:
list1andlist2They are 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 a list.- Finally, print the union list.
Output:
[1, 2, 3, 4, 5, 6, 7, 8]Other Extensions
Python3 Examples