Python • Collections and Strings

Set Operations — Perform set operations (union, intersection, difference) (intro)

Learn how Python sets let you combine, overlap, and subtract collections of unique items with elegant one-line operations.

Code braces with terminal and markup symbols representing Python programming.
Inside this lesson 10 sections 5 questions 9 figures

SECTION 1

Historical Context & Motivation

Before computers ever existed, mathematicians needed a way to reason about groups of objects. In the 1870s, German mathematician Georg Cantor formalized the idea of a set — an unordered collection of distinct elements. His work became the foundation of modern mathematics and, eventually, the data structures you use in programming today.

Fast forward to the age of computing, and sets turned out to be incredibly useful for tasks like removing duplicates from data, checking membership quickly, and combining or comparing groups of items. Python introduced a built-in set type to give programmers direct access to these powerful mathematical operations.

1874 • Cantor Founds Set Theory

Georg Cantor publishes his groundbreaking paper on set theory, defining sets as collections of distinct objects and establishing the operations of union, intersection, and difference.

1880s • Venn Diagrams Emerge

John Venn popularizes overlapping circle diagrams to visualize set relationships, giving students and researchers an intuitive way to understand set operations.

1960s • Sets Enter Programming

Languages like SETL (Set Language) introduce set-based data structures into computing, demonstrating the power of mathematical sets for solving algorithmic problems.

2004 • Python Adds Built-in Sets

Python 2.4 introduces the built-in set type with full support for union, intersection, and difference, making set operations accessible to all Python programmers.

The core question that set operations answer is simple but powerful: given two or more groups of items, how can you efficiently combine them, find what they share, or figure out what's unique to each group? Python's set type makes these tasks surprisingly straightforward.

SECTION 2

Core Principles & Definitions

Before diving into operations, you need to understand what makes a Python set special. A set is an unordered collection where every element appears exactly once. You create one with curly braces or the set() constructor. Once you have two or more sets, three fundamental operations let you combine and compare them.

1

Union ( | )

Combines all elements from both sets into a single new set. If an element appears in either set (or both), it shows up in the result. Think of it as merging two guest lists — everyone is invited.
2

Intersection ( & )

Keeps only the elements that appear in both sets. This operation finds the overlap — the items the two sets have in common, like friends that two people share.
3

Difference ( - )

Returns elements that are in the first set but not in the second. Order matters here — A − B gives you what's unique to A. Think of it as "what do I have that you don't?"
4

No Duplicates

Sets automatically discard duplicate values. If you add the same element twice, the set stores it only once. This property is what makes set operations clean and predictable.
✦

KEY TAKEAWAY

Think of sets like circles on a Venn diagram. Union is the entire shaded area of both circles. Intersection is just the overlap in the middle. Difference is one circle with the overlap erased. If you can picture a Venn diagram, you already understand set operations!

SECTION 3

Visual Explanation — Venn Diagrams for Set Operations

The best way to understand set operations is to see them. The diagram below shows two sets, A and B, as overlapping circles. Each operation highlights a different region of the diagram.

Set Operations — Venn Diagram OverviewUNION (A | B)ABEverything shadedINTERSECTION (A & B)ABOnly the overlapDIFFERENCE (A - B)ABA only (no overlap)Concrete ExampleA = {1, 2, 3, 4} B = {3, 4, 5, 6}123456Set ASet B
Top row: abstract Venn diagrams showing the shaded region for each operation. Bottom: a concrete example with A = {1, 2, 3, 4} and B = {3, 4, 5, 6}. The elements 3 and 4 sit in the overlap (intersection), while 1 and 2 are unique to A and 5 and 6 are unique to B.

In the concrete example, union gives {1, 2, 3, 4, 5, 6} — every element from both sets. Intersection gives {3, 4} — only the shared elements. Difference A − B gives {1, 2} — what A has that B doesn't. Notice that B − A would give {5, 6} instead, since difference depends on order.

SECTION 4

Python Syntax — Operators and Methods

Python gives you two ways to perform each set operation: a symbolic operator and a named method. Both produce the same result, so choose whichever makes your code clearer. The operator versions are shorter, while the method versions accept any iterable (like a list), not just sets.

UNION

A∣B→A.union(B)A | B → A.union(B)

Returns a new set containing every element found in A, in B, or in both. Neither A nor B is modified.

INTERSECTION

A & B → A.intersection(B)

Returns a new set containing only elements present in both A and B. Elements unique to either set are excluded.

DIFFERENCE

A−B→A.difference(B)A - B → A.difference(B)

Returns a new set containing elements that are in A but not in B. The order matters — A − B ≠ B − A in general.

SYMMETRIC DIFFERENCE (BONUS)

AB→A.symmetricdifference(B)A ^ B → A.symmetric_difference(B)

Returns elements in A or B, but not in both. This is the union minus the intersection — everything that's unique to one set or the other.

💡

Operator vs. Method

The | operator requires both sides to be sets. The .union() method can accept a list, tuple, or any iterable as its argument — Python converts it to a set internally. For example, {1, 2}.union([2, 3]) works, but {1, 2} | [2, 3] raises a TypeError.

SECTION 5

Detailed Breakdown — Common Code Patterns

Let's look at how these operations appear in real Python code. Each example creates two sets and applies all three core operations. The diagram below maps Python code to the results it produces.

Python Set Operations — Code → Result FlowDEFINE SETSfruits = {"apple", "banana", "cherry"}citrus = {"orange", "lemon", "cherry"}"cherry" is in both setsUNIONfruits | citrus{"apple","banana","cherry","orange","lemon"}INTERSECTIONfruits & citrus{"cherry"}DIFFERENCEfruits - citrus{"apple", "banana"}Real-World Scenario: Student Club Membershipchess_club = {"Alice", "Bob", "Carol", "Dave"}debate_club = {"Carol", "Dave", "Eve", "Frank"}all_members = chess_club | debate_club→ 6 unique studentsboth_clubs = chess_club & debate_club→ {"Carol", "Dave"}chess_only = chess_club - debate_club→ {"Alice", "Bob"}one_club = chess_club ^ debate_club→ {"Alice","Bob","Eve","Frank"}^ = symmetric difference: students in exactly one club
Top: defining two sets with a shared element. Middle row: each operation applied with its result. Bottom: a school club scenario showing how set operations solve real membership questions.
OperationOperatorMethodReturns
UnionA | BA.union(B)All elements from A and B
IntersectionA & BA.intersection(B)Elements in both A and B
DifferenceA - BA.difference(B)Elements in A but not in B
Symmetric Diff.A ^ BA.symmetric_difference(B)Elements in A or B, not both

Quick reference: all four set operations with their operator and method syntax.

SECTION 6

Worked Example — Playlist Merging

Imagine you and a friend each have a music playlist stored as a Python set. You want to find all unique songs across both playlists, the songs you both like, and the songs only you have. Let's walk through this step by step.

Merging Two Music Playlists

  1. 1

    Step 1 — Define the sets

    Create two sets representing each playlist. Note that sets use curly braces and hold unique string values. my_songs = {"Blinding Lights", "Levitating", "Watermelon Sugar", "Peaches"} friend_songs = {"Levitating", "Peaches", "Stay", "Good 4 U"}
    Two sets created: my_songs has 4 elements, friend_songs has 4 elements.
  2. 2

    Step 2 — Find all unique songs (Union)

    Use the | operator to combine both playlists. Duplicates are automatically removed. all_songs = my_songs | friend_songs
    {"Blinding Lights", "Levitating", "Watermelon Sugar", "Peaches", "Stay", "Good 4 U"} — 6 unique songs total.
  3. 3

    Step 3 — Find shared favorites (Intersection)

    Use the & operator to find songs that appear in both playlists. shared = my_songs & friend_songs
    {"Levitating", "Peaches"} — the 2 songs you both enjoy.
  4. 4

    Step 4 — Find songs only you have (Difference)

    Use the - operator. Since we write my_songs - friend_songs, we get elements in my_songs that are NOT in friend_songs. only_mine = my_songs - friend_songs
    {"Blinding Lights", "Watermelon Sugar"} — songs only on your playlist.
  5. 5

    Step 5 — Verify with len()

    A useful check: the size of the union should equal the size of A plus the size of B minus the size of the intersection (to avoid double-counting). We have len(all_songs) = 6, and 4 + 4 − 2 = 6. ✓ The math confirms our results are correct.
    |A ∪ B| = |A| + |B| − |A ∩ B| → 6 = 4 + 4 − 2 ✓

SECTION 7

Sets vs. Lists vs. Dictionaries

Python offers several collection types, and choosing the right one matters. Sets are the best tool when you care about uniqueness and membership testing, but they have trade-offs compared to lists and dictionaries. The table below highlights the key differences.

FeatureSetListDictionary
Duplicates allowed?NoYesNo (keys)
Ordered?NoYesInsertion order (3.7+)
Membership check speedO(1) averageO(n)O(1) average
Built-in set operations?YesNoNo
Index access (e.g., [0])?NoYesBy key

Comparison of Python's three main collection types.

🎯

WHEN TO USE A SET

Use a set when you need to answer questions like "Is this item in the group?" or "What do these two groups have in common?" Think of a set like a bag of unique stickers — you can quickly check if you already have one, compare your collection with a friend's, or combine collections without worrying about duplicates. If order or duplicates matter, reach for a list instead.

SECTION 8

Connection to Advanced Concepts

The set operations you've learned here are just the beginning. As you advance in computer science, you'll encounter these same ideas in increasingly powerful contexts. Database queries use set-like operations (SQL's UNION, INTERSECT, and EXCEPT), and understanding sets will help you write efficient algorithms for searching and filtering data.

Introductory ConceptAdvanced Extension
Basic set operations (|, &, -)frozenset — an immutable set you can use as a dictionary key or put inside another set
Creating sets manuallySet comprehensions — e.g., {x**2 for x in range(10)} builds sets dynamically
Comparing two setsSubset/superset checks — A.issubset(B) and A.issuperset(B) test containment
Set difference for filteringDatabase EXCEPT/MINUS operations and relational algebra in SQL
Membership check (in)Hash tables — the data structure underlying sets, enabling O(1) lookups

How today's concepts connect to more advanced topics.

Once you're comfortable with the basics, try chaining operations together. For example, (A | B) - (A & B) is equivalent to the symmetric difference A ^ B. Discovering these relationships deepens your understanding of how set operations relate to each other and to Boolean logic.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words why the order of the operands matters for set difference but does not matter for union or intersection. Give a brief example to support your answer.
Show answer
Union and intersection are commutative — A | B and B | A both produce the same set because they consider all elements or shared elements regardless of which set is "first." Difference, however, asks "what is in the first set but not the second," so the starting set matters. For example, if A = {1, 2, 3} and B = {2, 3, 4}, then A − B = {1} but B − A = {4}. The results are different because each operation removes elements found in the other set, and the two sets contribute different unique elements.

Question 2: BASIC CALCULATION

Given x = {10, 20, 30, 40} and y = {30, 40, 50, 60}, determine the result of each: (a) x | y, (b) x & y, (c) x - y.
Show answer
(a) x | y = {10, 20, 30, 40, 50, 60} — all elements from both sets combined, with duplicates removed. (b) x & y = {30, 40} — only 30 and 40 appear in both sets. (c) x - y = {10, 20} — 10 and 20 are in x but not in y. The shared elements (30 and 40) are removed by the difference operation.

Question 3: INTERMEDIATE

You have three sets: a = {1, 2, 3, 4, 5}, b = {4, 5, 6, 7}, and c = {5, 6, 7, 8, 9}. Write a Python expression to find elements that are in all three sets. Then write another expression to find elements that are in at least one of the three sets.
Show answer
To find elements in all three sets (intersection of all three): a & b & c which yields {5}, since 5 is the only element present in a, b, and c. To find elements in at least one set (union of all three): a | b | c which yields {1, 2, 3, 4, 5, 6, 7, 8, 9}. Python allows chaining set operators, and they evaluate left to right. You can also write these using the method syntax: a.intersection(b, c) and a.union(b, c) — notice the methods can accept multiple arguments.

Question 4: APPLIED

A teacher stores students who passed a math exam and a science exam in two sets: math_pass = {"Ana", "Ben", "Cara", "Dan", "Eve"} and sci_pass = {"Ben", "Cara", "Fay", "Gus"}. Write Python code to find: (a) students who passed both exams, (b) students who passed math but not science, and (c) the total number of students who passed at least one exam.
Show answer
(a) both = math_pass & sci_pass → {"Ben", "Cara"}. These two students passed both exams. (b) math_only = math_pass - sci_pass → {"Ana", "Dan", "Eve"}. These three passed math but not science. (c) len(math_pass | sci_pass) → 7. The union contains Ana, Ben, Cara, Dan, Eve, Fay, and Gus. Using len() on the union gives the count. You can verify: 5 + 4 − 2 = 7, matching the formula |A ∪ B| = |A| + |B| − |A ∩ B|.

Question 5: CRITICAL THINKING

A programmer claims that (A - B) | (B - A) always produces the same result as A ^ B (symmetric difference). Is this claim correct? Prove your reasoning by testing with A = {1, 2, 3} and B = {2, 3, 4}, and then explain why the relationship holds (or doesn't) for any two sets.
Show answer
The claim is correct. With A = {1, 2, 3} and B = {2, 3, 4}: A − B = {1} (elements only in A), B − A = {4} (elements only in B), and (A − B) | (B − A) = {1, 4}. Meanwhile, A ^ B = {1, 4}. They match. This works for any two sets because symmetric difference is defined as elements in exactly one of the two sets. A − B captures elements exclusive to A, and B − A captures elements exclusive to B. Their union gives all elements that are in one set but not both — which is exactly the definition of symmetric difference. You can also express this as (A | B) − (A & B), which takes the full union and removes the shared elements, arriving at the same result.

SUMMARY

Lesson Summary

Summary

Python sets are unordered collections of unique elements that support three core operations: union (|) combines all elements from both sets, intersection (&) keeps only shared elements, and difference (-) returns elements in the first set but not the second. Each operation has both an operator and a method form, and none of them modify the original sets.

Sets excel at fast membership testing (O(1) on average) and automatic deduplication. Remember that difference is order-dependent (A − B ≠ B − A), while union and intersection are not. The bonus symmetric difference (^) gives elements in exactly one set. These operations form the foundation for database queries, data cleaning, and algorithmic problem-solving you'll encounter in more advanced courses.

Varsity Tutors • Python • Set Operations — Perform set operations (union, intersection, difference) (intro)