Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Use a Set to Find the Union of Two Lists

Python Use a Set to Find the Union of Two Lists

Document Object Reference Manual 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 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

)

print

(

union_list

)

Code analysis:

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

Output result:

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

Document Object Reference Manual Python3 Examples