The union method

The union method returns a set obtained by combining the elements of the sets specified in the parameter.

Syntax

pythonset.union(sets we want to unite)

Example

Let's apply the union method to get the common elements of two sets:

pythonst1 = {'a', 'b', 'c'}
st2 = {'1', '2', '3'}
res = st1.union(st2)
print(res)

Result of code execution:

python{'c', '2', 'b', '1', 'a', '3'}

Example

The union method also has a short form:

pythonst1 = {'a', 'b', 'c'}
st2 = {'1', '2', '3'}
res = st1 | st2
print(res)

Result of code execution:

python{'a', '1', 'b', '3', '2', 'c'}

See also

  • method add,
    which adds elements to a set
  • method update,
    which adds elements from other sets
  • method remove,
    which removes elements from a set
  • function len,
    which returns the length of the set