How to Union Multiple Sets in Python?

The most efficient way to join multiple sets (stored in a list of sets), use the Python one-liner set().union(*list) that creates a new set object, calls the union() method on the new object, and unpacks all sets from the list of sets into the union() method’s argument list.

A set is a unique collection of unordered elements. The union operation combines all elements of two sets into a new set—removing all duplicate entries in the process.

In the following video, you can watch me explain how to union multiple sets in Python:

So, let’s dive into the formal problem formulation, shall we?

Problem: Given a list or a collection of sets. How to join those sets using the union operation?

Example: You’ve got a list of sets [{1, 2, 3}, {1, 4}, {2, 3, 5}] and you want to calculate the union {1, 2, 3, 4, 5}.

Solution: To union a list of sets, use the following strategy:

  • Create a new set using the set() constructor.
  • Call the union() method on the new set object.
  • Pass all sets as arguments into the union() method by unpacking the list with the asterisk operator *list.
  • The result of the union() method is a new set containing all elements that are in at least one of the sets.

Code: Here’s the one-liner code that unions a collection of sets.

# Create the list of sets
lst = [{1, 2, 3}, {1, 4}, {2, 3, 5}]

# One-Liner to union a list of sets
print(set().union(*lst))

The output of this code is the union of the three sets {1, 2, 3}, {1, 4}, {2, 3, 5}:

{1, 2, 3, 4, 5}

If you love Python one-liners, check out my new book “Python One-Liners” (Amazon Link) that teaches you a thorough understanding of all single lines of Python code.

Try it yourself: Here’s the code in an interactive code shell that runs it in your browser:

Exercise: Change the code to calculate the intersection of the sets in the list!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!