Skip to content

Module 8 · Python Data Structures — topic 14 of 22

Union

The union of sets contains every item that appears in at least one of them. Learn |, union() with several arguments, in-place update(), and practical uses in merging and deduplicating data.

Beginner 8 min read·Lesson 117 of 306 in Python Programming

Learning objectives

  • Combine sets with | and union()
  • Merge several collections at once
  • Update a set in place with |= or update()

Definition

The union of sets contains every item that appears in at least one of them. Learn |, union() with several arguments, in-place update(), and practical uses in merging and deduplicating data.

Introduction

The union of two sets is a set of everything that appears in either one. Duplicates collapse, so each item appears once. {1, 2} | {2, 3} is {1, 2, 3}.

Why it matters

Merging lists of subscribers, combining tags from several articles or gathering all the skills in a team are all unions: you want everything, once.

Detailed explanation

a | b returns a new set containing every item from a and b.

a.union(b, c, d) accepts several iterables at once, including lists and tuples.

a |= b or a.update(b) adds the items of b to a in place, without creating a new set.

The size of a union is at most len(a) + len(b) and at least the larger of the two; it is smaller when they overlap.

Union is commutative: a | b equals b | a.

When order matters, for example merging lists while keeping first-seen order, a set alone isn’t enough; combine a set for “seen” with a list for order, as in the sets lesson.

Syntax

Python
everyone = a | b
everyone = a.union(b, c)
a |= b
a.update(list_of_items)
  • | returns a new set.
  • union() accepts many iterables.
  • |= and update() change the left set.

Code examples

Union with operator and method

Python
morning = {"Asha", "Ben"}
evening = {"Ben", "Chen"}
print(sorted(morning | evening))
print(sorted(morning.union(["Dev"], ("Esha",))))
Output
['Asha', 'Ben', 'Chen']
['Asha', 'Ben', 'Dev', 'Esha']

In-place union

Python
skills = {"python"}
skills |= {"sql"}
skills.update(["git", "python"])
print(sorted(skills))
Output
['git', 'python', 'sql']

More examples

Merging mailing lists

Python
newsletter = ["a@x.com", "b@x.com"]
webinar = ["B@x.com ", "c@x.com"]
course = ["c@x.com", "d@x.com", "a@x.com"]
def clean(emails):
return {e.strip().lower() for e in emails}
all_contacts = clean(newsletter) | clean(webinar) | clean(course)
print(len(newsletter) + len(webinar) + len(course), "entries")
print(len(all_contacts), "unique contacts:", sorted(all_contacts))
Output
7 entries
4 unique contacts: ['a@x.com', 'b@x.com', 'c@x.com', 'd@x.com']

Step-by-step explanation

  • clean() normalises each email with strip() and lower() in a set comprehension.
  • Without cleaning, "B@x.com " and "b@x.com" would be counted as different.
  • Chained | merges all three cleaned sets.
  • Seven entries collapse to four unique contacts.

Expected output

Running “Merging mailing lists” prints exactly:

TextOutput
7 entries
4 unique contacts: ['a@x.com', 'b@x.com', 'c@x.com', 'd@x.com']

Practical applications

  • Marketing tools merge contact lists from several campaigns.
  • Search engines combine results from several indexes.
  • Teams combine skill sets to see their total capabilities.

Best practices

  • Normalise values before merging.
  • Use union() to merge many iterables at once.
  • Use update() to grow a set over time.

Common mistakes

Using + on sets

Avoid

{1, 2} + {3}

Prefer

{1, 2} | {3}

Sets don’t support +; use | or union().

Merging without normalising

Avoid

set(list_a) | set(list_b) # "A@x.com" and "a@x.com" both kept

Prefer

Normalise case and spaces first.

Sets compare exact values.

Key takeaways

  • Union contains items in either set, once each.
  • | and union() return new sets; |= and update() change in place.
  • union() accepts lists and multiple arguments.

Try it yourself

  1. 1
    Merge three lists of city names into one set and print them sorted.
  2. 2
    Keep a growing set of all words seen across several sentences using update().

Finished reading? Mark it complete to update your dashboard.

Suggested practice

13 questions cover the “Python Data Structures” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module