.union()
BrandonDusch580 total contributions
Published May 23, 2022
Contribute to Docs
The .union()
method returns a new set that combines objects from all sets involved, removing any duplicates.
Syntax
The following syntaxes can be used:
set.union(set1, set2, ..., setN)
setA | setB | setC
- The
.union()
method can be called directly againstset
with multiple sets passed as arguments. - Optionally, the
|
operator can be used between setssetA
,setB
, andsetC
where it will return the same result as the.union()
method.
Example
In the example below, two sets of liked_artists
are created using two alternate syntaxes. Next, they are combined and stored in a new set, all_likes
, using the .union()
method:
liked_artists_1 = {'Grimes', 'Billie Eilish'}liked_artists_2 = {'Daft Punk', 'Iggy Azalea'}all_likes = liked_artists_1.union(liked_artists_2)print(all_likes)
The output would be the following:
{'Iggy Azalea', 'Daft Punk', 'Grimes', 'Billie Eilish'}
Codebyte Example
In this example, a new set, three_Bs
, is created with the alternative syntax of the .union()
method:
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.