set.union()

Returns a new set with the elements from every given set, without duplicates.

Returns
A new set.
Changes the original
No
On this page

Example

#
Python
emma = {"HTML", "CSS", "Python"}
jack = {"Python", "React"}

together = emma.union(jack)
print(sorted(together))
print(sorted(emma | jack))
print(len(emma), len(jack), len(together))
Resultsaved result, you can check it
['CSS', 'HTML', 'Python', 'React']
['CSS', 'HTML', 'Python', 'React']
3 2 4

Definition and usage

#

The union() method builds the union of sets: a new set with every element that appears in any of them. Elements present in several sets appear only once in the result, and the originals stay unchanged.

The | operator gives the same result: a | b. The method has two advantages, though: it accepts several arguments at once, and it accepts any collection, such as a list, while the operator requires sets on both sides.

If you want to add elements to an existing set instead of creating a new one, use the update() method or the |= operator.

Syntax

#
Syntax
set.union(*others)
set | other

Parameters

#
  • *others

    sets or other collections

    The collections whose elements will join the result.

More examples

#
Several collections at once
Python
tags = {"python"}
print(sorted(tags.union(["html", "css"], ("python", "sql"))))

try:
    tags | ["html"]
except TypeError as error:
    print(error)
Resultsaved result, you can check it
['css', 'html', 'python', 'sql']
unsupported operand type(s) for |: 'set' and 'list'
Adding to an existing set
Python
skills = {"python"}

skills |= {"git"}
skills.update(["docker", "git"])
print(sorted(skills))
Resultsaved result, you can check it
['docker', 'git', 'python']

Good practices

#
  • Use the union() method to combine with a list or tuple. The | operator only works when both sides are sets.
  • The result has no fixed order. If you show it to a user, sort it with sorted().

Related entries

#

Spotted a mistake or missing an example? Write to us.