What is Python Set Union ?

Answer : The union() method returns a new set with distinct elements from each and every one of the sets.

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

[pastacode lang=”markdown” manual=”A%20%3D%20%7B’a’%2C%20’c’%2C%20’d’%7D%0AB%20%3D%20%7B’c’%2C%20’d’%2C%202%20%7D%0AC%3D%20%7B1%2C%202%2C%203%7D%0Aprint(‘A%20U%20B%20%3D’%2C%20A%7C%20B)%0Aprint(‘B%20U%20C%20%3D’%2C%20B%20%7C%20C)%0Aprint(‘A%20U%20B%20U%20C%20%3D’%2C%20A%20%7C%20B%20%7C%20C)” message=”” highlight=”” provider=”manual”/]

Output

[pastacode lang=”markdown” manual=”A%20U%20B%20%3D%20%7B2%2C%20’a’%2C%20’c’%2C%20’d’%7D%0AB%20U%20C%20%3D%20%7B1%2C%202%2C%203%2C%20’c’%2C%20’d’%7D%0AA%20U%20B%20U%20C%20%3D%20%7B1%2C%202%2C%203%2C%20’a’%2C%20’c’%2C%20’d’%7D” message=”” highlight=”” provider=”manual”/]
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like