PythonDictionaries and sets
set. union()
Returns a new set with the elements from every given set, without duplicates.
- Returns
- A new set.
- Changes the original
- No
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 | otherParameters
#*others
sets or other collections
The collections whose elements will join the result.
More examples
#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'
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
#- set.intersection()Returns a new set with the elements that appear in every given set.
- set.difference()Returns a new set with the elements of the first set that are not in the others.
- set.add()Adds an element to a set. If the element is already there, the set doesn't change.
- set()Creates a set: an unordered collection of unique items.
- dict.update()Adds pairs from another dictionary or from arguments to a dictionary, overwriting existing keys.
Spotted a mistake or missing an example? Write to us.