Python .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 againstsetwith multiple sets passed as arguments. - Optionally, the
|operator can be used between setssetA,setB, andsetCwhere 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:
Contribute to Docs
- 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.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours