Python Set Union

  • The union() method returns a new set with distinct elements from each and every one of the sets.
  • The union of two or more sets is the set of all distinct elements shown in all the sets.
Python set union

Learn python – python tutorial – python set union – python examples – python programs

Example:

    • A = {1, 2}
    • B = {2, 3, 4}
    • C = {5}

Then,

  • A∪B = B∪A ={1, 2, 3, 4}
  • A∪C = C∪A ={1, 2, 5}
  • B∪C = C∪B ={2, 3, 4, 5}
  • A∪B∪C = {1, 2, 3, 4, 5}

Syntax:

S.union(t)

Set Union Using | Operator

A = {'a', 'c', 'd'}
B = {'c', 'd', 2 }
C= {1, 2, 3}
print('A U B =', A| B)
print('B U C =', B | C)
print('A U B U C =', A | B | C)

Output

A U B = {2, 'a', 'c', 'd'}
B U C = {1, 2, 3, 'c', 'd'}
A U B U C = {1, 2, 3, 'a', 'c', 'd'}

Categorized in:

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,