Python Using Sets to Find the Union of Two Lists

Document 对象参考手册Python3 Examples

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)

Code explanation:

  1. list1andlist2They are two lists containing duplicate elements.
  2. set(list1)andset(list2)Convert the lists to sets, automatically removing duplicate elements.
  3. set1.union(set2)Use the set'sunionmethod to find the union of the two sets.
  4. list(union_set)Convert the union set back to a list.
  5. Finally, print the union list.

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

Document 对象参考手册Python3 Examples

Other Extensions