.union()

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 against set with multiple sets passed as arguments.
  • Optionally, the | operator can be used between sets setA, setB, and setC 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:

Code
Output
Loading...

All contributors

Looking to contribute?

Learn Python on Codecademy