Python Union

In the last lesson you learned about Set Operations and got a feel for how sets work together. Now we will slow down and look at the first one closely. It is called union. It answers a question everybody runs into. How do I put two groups together into one?

πŸ€” Why Union?

Say you have two guest lists. One list is people who like tea. The other is people who like coffee. You want one single list of everyone who likes tea or coffee. Some people like both. So they show up on both lists. You do not want their name written twice.

Doing this by hand is slow and easy to get wrong. So think about what you would have to do:

  • You would copy the first list, then go through the second list one name at a time.
  • For each name you would stop and check, is this person already on my combined list?
  • If yes, you skip them. If no, you add them.

That checking step is the boring part, and it is where mistakes creep in. Union does all of it for you in one line. It joins the two sets, then drops the repeats automatically.

🧩 What Union Means

Union takes two sets and gives you a new set with every item from both. If an item is in both sets, it still appears only once. That is the whole idea.

Think of it like merging two contact lists on your phone. If the same person is in both, you do not want two copies. You want one clean list with everybody on it. That is union.

One thing to keep in mind. Union does not change your original sets. It builds and returns a new set. Your two starting sets stay exactly as they were.

πŸ› οΈ Two Ways to Do It

Python gives you two ways to write a union. Both do the same job. So you can pick whichever reads better to you.

This table shows them side by side.

Way Looks like Good when
The union() method a.union(b) You want clear, readable words
The | operator a | b You want short and quick

β˜• A Real Example

Here are our two groups. One set holds people who like tea. The other holds people who like coffee. Notice that Riya likes both.

This code creates the two sets and joins them with the union() method.

tea = {"Alex", "Riya", "Arjun"}
coffee = {"Riya", "Maya", "Sam"}
everyone = tea.union(coffee)
print(everyone)

The result is a new set with everybody in it. Riya is in both groups. But she shows up only once.

Output

{'Alex', 'Riya', 'Arjun', 'Maya', 'Sam'}

Note

Sets have no fixed order. So the names may print in a different order on your machine. That is normal. What matters is that every name is there and no name repeats.

Now the same thing with the | operator. It does exactly the same work, just shorter.

tea = {"Alex", "Riya", "Arjun"}
coffee = {"Riya", "Maya", "Sam"}
everyone = tea | coffee
print(everyone)

You get the same combined set. Pick the style you like and stay with it.

Output

{'Alex', 'Riya', 'Arjun', 'Maya', 'Sam'}

πŸ”— Joining Three or More Sets

Real life is not always just two groups. So what if you have three? Maybe one more group of people who like juice. You do not need to call union twice. You can join them all in one go.

This code joins three sets at once with the | operator.

tea = {"Alex", "Riya", "Arjun"}
coffee = {"Riya", "Maya", "Sam"}
juice = {"Sam", "Neha"}
everyone = tea | coffee | juice
print(everyone)

Python reads tea | coffee | juice left to right. So it joins tea and coffee first, then joins juice onto that result. Sam is in both coffee and juice, so Sam still shows up only once.

Output

{'Alex', 'Riya', 'Arjun', 'Maya', 'Sam', 'Neha'}

The union() method can do the same thing. The nice part is you can pass it more than one set at a time. So you just list them, separated by commas.

everyone = tea.union(coffee, juice)
print(everyone)

Both lines give you the exact same combined set. So when you have a chain of groups, you do not need a separate step for each one. One line handles all of them.

πŸ“₯ Changing the Original with update()

So far every union built a brand new set and left the originals alone. But sometimes you do not want a new set. You just want to pour the second set into the first one and keep going with that. For that, there is update().

Here update() adds everything from coffee straight into tea.

tea = {"Alex", "Riya", "Arjun"}
coffee = {"Riya", "Maya", "Sam"}
tea.update(coffee)
print(tea)

After this line, tea itself has grown. It now holds every name from both groups. There is no new variable. The change happened right inside tea.

Output

{'Alex', 'Riya', 'Arjun', 'Maya', 'Sam'}

There is a short way to write the same thing. The |= operator does exactly what update() does.

tea |= coffee

So now there are two pairs to keep straight. Here is the difference in one place:

  • a.union(b) and a | b build a new set and hand it back. Your original a stays the same. You must store the result in a variable or it is gone.
  • a.update(b) and a |= b change a in place. There is no new set. The old a is replaced by the bigger one.

So which one do you reach for? Use union when you want to keep the originals safe and get a fresh result. Use update when you are building up one set step by step and do not care about keeping the old smaller version.

πŸ“‹ Union With a List, Not Just a Set

Here is a handy thing the union() method can do that the | operator cannot. The method does not insist that the other side is a set. You can pass it a list, a tuple, or any group you can loop over.

This code unions a set with a plain list.

tea = {"Alex", "Riya", "Arjun"}
new_people = ["Riya", "Maya"]
everyone = tea.union(new_people)
print(everyone)

It works fine. Python reads through the list, adds each name, and skips Riya because she is already there. You still get a clean set with no repeats.

Output

{'Alex', 'Riya', 'Arjun', 'Maya'}

But the | operator is stricter. It needs a set on both sides. So if you try the pipe with a list, Python stops you.

# ❌ Avoid: the pipe needs a set on both sides
everyone = tea | ["Riya", "Maya"] # TypeError

Caution

The | operator only joins set with set. If one side is a list or a tuple, you get a TypeError. So when your other group is a list, use the union() method, or wrap the list in set(...) first like tea | set(new_people).

πŸ”Ž The Originals Stay Safe

Let us prove that plain union does not touch your starting sets. After the union, we print the originals again.

tea = {"Alex", "Riya", "Arjun"}
coffee = {"Riya", "Maya", "Sam"}
everyone = tea | coffee
print(len(everyone))
print(tea)
print(coffee)

The combined set has five names. And tea and coffee are still untouched. Each one still has its own three names.

Output

5
{'Alex', 'Riya', 'Arjun'}
{'Riya', 'Maya', 'Sam'}

πŸ‘₯ Another Real Example: Unique Visitors

The tea and coffee story is friendly, but union shows up in real code all the time. So here is a second one you will actually meet.

Say you run a small website. You keep track of who logged in each day. On Monday some people visited. On Tuesday some people visited. A few of them came both days. Now your manager asks, how many different people visited across the two days? Not the total visits, the number of unique people.

This is union, exactly. You join the two days and the repeats drop out on their own.

monday = {"alex_99", "riya_k", "arjun_m", "sam"}
tuesday = {"riya_k", "neha", "sam", "maya"}
visitors = monday | tuesday
print("Unique people:", len(visitors))
print(visitors)

Walk through it:

  • monday holds the four user IDs who came on Monday.
  • tuesday holds the four who came on Tuesday, but riya_k and sam are in both days.
  • monday | tuesday joins them. The two shared IDs are counted once, not twice.
  • len(visitors) then tells you how many different people there were in total.

Output

Unique people: 6
{'alex_99', 'riya_k', 'arjun_m', 'sam', 'neha', 'maya'}

Eight visits happened across the two days. But only six different people. Union gave you that number with no manual counting. The same trick works for merging tags on two posts, or merging the permissions from two user roles into one. Anywhere you mean β€œeverything from both, but each thing once”, union is the tool.

⚑ Why Union Is Fast and What You Get Back

You might wonder how Python skips the repeats so quickly. So here is the short version.

  • A set is stored in a special way that lets Python check β€œis this item already in here?” almost instantly. It does not scan the whole set every time. That quick check is why union can drop duplicates fast even on large groups.
  • Plain union always hands you back a brand new set. The type you get is still set. So type(tea | coffee) is set, and you can run more set operations on it right away.

This little check confirms the result is a set, not a list or anything else.

result = tea | coffee
print(type(result))

Output

<class 'set'>

So whatever you union, you stay in set world. That means no duplicates, fast membership checks, and all the other set operations are still available on the result.

⚠️ Common Mistakes

A few small things trip people up. Watch out for these.

  • Expecting duplicates in the result. Union always removes repeats. So if you actually need to count repeats, a set is the wrong tool.

  • Thinking plain union changes your original sets. It does not. Union returns a new set. So you must store it in a variable to keep it.

# ❌ Avoid: throwing the result away
tea.union(coffee) # the combined set is lost
# βœ… Good: save the result
everyone = tea.union(coffee)
  • Mixing up union() and update(). They look similar but they are not the same. One gives you a new set, the other changes the original.
# ❌ Avoid: expecting update() to return the combined set
everyone = tea.update(coffee) # everyone is None, tea changed instead
# βœ… Good: update() changes tea in place, so use tea after
tea.update(coffee)
print(tea)
  • Mixing up the symbols. Union uses | (the pipe). It is not +. Using + on two sets raises an error.
# ❌ Avoid: this is an error
combined = tea + coffee # TypeError
# βœ… Good: use the pipe for union
combined = tea | coffee
  • Using | with a list. The pipe needs a set on both sides. So with a list, use the union() method instead.
# ❌ Avoid: the pipe rejects a list
combined = tea | ["Maya"] # TypeError
# βœ… Good: the method accepts a list
combined = tea.union(["Maya"])

βœ… Best Practices

  • Use | for quick, short code and union() when you want the word to read clearly. Either is fine.
  • Always store the result of a plain union in a variable, since it gives you a new set.
  • Reach for update() (or |=) when you want to grow one set in place and do not need to keep the smaller original.
  • When your other group is a list or a tuple, use the union() method, since | only joins set with set.
  • Join three or more groups in one line with a | b | c or a.union(b, c). No need for a separate step per group.
  • Reach for union whenever you mean β€œeverything from both groups, no repeats”. Naming it in your head helps you pick the right operation.

🧩 What You’ve Learned

βœ… Union combines two sets into one new set with every item from both.

βœ… Duplicates are removed automatically, so each item appears only once.

βœ… You can write it as a.union(b) or with the | operator, and both do the same thing.

βœ… You can join three or more sets at once with a | b | c or a.union(b, c).

βœ… Plain union returns a new set and leaves your originals unchanged, while update() and |= change the original set in place.

βœ… The union() method accepts a list or tuple, but the | operator needs a set on both sides.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What does a union of two sets give you?

    Why: Union builds a new set containing all items from both sets, with any repeats removed.

  2. 2

    How is a.update(b) different from a.union(b)?

    Why: update() (and |=) grows the original set a in place and returns None, while union() (and |) builds and returns a brand new set, leaving a unchanged.

  3. 3

    Which of these works to union a set with a plain list?

    Why: The union() method accepts any iterable like a list or tuple. The | operator needs a set on both sides, so tea | ["Maya"] raises a TypeError.

  4. 4

    How do you join three sets a, b, and c into one with the pipe operator?

    Why: a | b | c chains the union left to right and gives one combined set with every item from all three, duplicates removed.

πŸš€ What’s Next?

You now know how to join two or more groups into one. Next we flip the question and find only the items that two sets share.

Intersection

Share & Connect