Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 3 · Sets

Sets

On this pageCreating SetsAccessing Set ItemsAdd Set ItemsRemove Set ItemsLoop SetsJoin SetsUnion – Combine All Unique ElementsIntersection – Find Common ElementsDifference – Find Unique Elements in One SetSymmetric Difference – Find Unshared ElementsUpdating Sets In PlaceFrozen SetsMini Project — Course Enrollment Analyzer

A set in Python is a collection of unique and unordered items. Unlike lists or tuples, sets automatically remove duplicates and do not preserve the order of elements. They are useful when you need to store distinct values, test membership quickly, or perform mathematical operations such as union and intersection.

Printed examples show one possible ordering. Your order may differ; compare the members rather than the printed positions. A pop() call can remove a different member in another run.

Creating Sets

Sets are defined using curly braces {} or the set() function.

fruits = {"apple", "banana", "cherry"}
print(fruits)
Listing 169 — Creating Sets

Output

{'apple', 'cherry', 'banana'}

You can also create an empty set, but remember to use set(), not {}, since {} creates an empty dictionary

empty_set = set()
print(type(empty_set))
Listing 170 — Creating Sets

Output

<class 'set'>

Accessing Set Items

Sets are unordered, so you cannot access items using an index like in lists or tuples. However, you can loop through them or check if an element exists using the in keyword.

fruits = {"apple", "banana", "cherry"}

print("banana" in fruits)   # check membership
print("orange" in fruits)
Listing 171 — Accessing Set Items

Output

True
False

Add Set Items

Sets provide methods for adding items. Use add() for adding a single element to a set and update() for adding multiple elements at once.

fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits)

fruits.update(["mango", "orange"])
print(fruits)
Listing 172 — Add Set Items

Output

{'apple', 'cherry', 'banana'}
{'apple', 'banana', 'cherry', 'mango', 'orange'}

Remove Set Items

There are several ways to remove items from a set:

  • .remove() – removes the item but raises an error if it does not exist.
  • .discard() – removes the item if present, but does nothing if not.
  • .pop() – removes and returns an arbitrary element; you cannot choose which one.
  • .clear() – removes all items.
  • del – removes a variable name; other names may still refer to the set.
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)

fruits.discard("pear")  # no error if missing
print(fruits)

removed = fruits.pop()
print("Removed:", removed)
print("Remaining:", fruits)

fruits.clear()
print("Cleared set:", fruits)
Listing 173 — Remove Set Items

Output

{'apple', 'cherry'}
{'apple', 'cherry'}
Removed: apple
Remaining: {'cherry'}
Cleared set: set()

Loop Sets

You can loop through a set using a simple for loop to access each element (we’ll explore loops in detail later).

colors = {"red", "green", "blue"}
for color in colors:
    print(color)
Listing 174 — Loop Sets

Output

blue
red
green

The order may vary because sets do not store elements in a specific sequence.

Join Sets

In Python, joining sets means combining or comparing their contents. This works exactly like mathematical set operations — allowing you to find elements that appear in one set, both sets, or only in one of them. Python provides several methods and operators to perform these joins efficiently.

Let’s start with two sets:

a = {1, 2, 3}
b = {3, 4, 5}
Listing 175 — Join Sets

Union – Combine All Unique Elements

The union of two sets returns a new set containing all unique elements from both. Duplicates are automatically removed.

print(a.union(b))
print(a | b)   # shorthand operator
Listing 176 — Union – Combine All Unique Elements

Output

{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}

The union() method and | operator produce the same result. Union is commonly used when merging datasets or aggregating results without duplicates — for example, combining customer lists from two regions.

Intersection – Find Common Elements

The intersection returns only elements that appear in both sets.

print(a.intersection(b))
print(a & b)   # shorthand operator
Listing 177 — Intersection – Find Common Elements

Output

{3}
{3}

This is useful when identifying overlap — such as shared courses between students or mutual friends between two users.

Difference – Find Unique Elements in One Set

The difference returns elements that are in the first set but not in the second.

print(a.difference(b))
print(a - b)   # shorthand operator
Listing 178 — Difference – Find Unique Elements in One Set

Output

{1, 2}
{1, 2}

If you reverse the order, the result changes:

print(b.difference(a))
Listing 179 — Difference – Find Unique Elements in One Set

Output

{4, 5}

Symmetric Difference – Find Unshared Elements

The symmetric difference returns all elements that are in either of the sets, but not in both.

print(a.symmetric_difference(b))
print(a ^ b)   # shorthand operator
Listing 180 — Symmetric Difference – Find Unshared Elements

Output

{1, 2, 4, 5}
{1, 2, 4, 5}

Use this method when you want to find mismatched or non-overlapping data — such as products unique to each store or topics not shared between two lists.

Updating Sets In Place

Instead of creating new sets, you can update an existing one using methods like:

  • update() — adds all elements from another set.
  • intersection_update() — keeps only elements found in both.
  • difference_update() — removes elements found in another set.
  • symmetric_difference_update() — keeps only unshared elements.
x = {1, 2, 3}
y = {3, 4, 5}

x.update(y)
print("After update:", x)

x = {1, 2, 3}
x.intersection_update(y)
print("After intersection_update:", x)
Listing 181 — Updating Sets In Place

Output

After update: {1, 2, 3, 4, 5}
After intersection_update: {3}

These in-place updates are efficient when working with large data collections where you do not need to keep the original set.

Frozen Sets

A frozenset is an immutable version of a set. Once created, its contents cannot be changed, making it safe for use as dictionary keys or fixed configurations.

numbers = frozenset({1, 2, 3, 4})
print(numbers)
Listing 182 — Frozen Sets

Output

frozenset({1, 2, 3, 4})

Attempting to modify it (for example,numbers.add(5)) will raise an error. Frozensets are especially useful in data integrity contexts where values must remain constant.

Mini Project — Course Enrollment Analyzer

Write a program that analyzes course enrollments for two students and reports shared, unique, and total courses using Python sets. This project puts set operations into practice to solve a realistic problem in academic data management.

Tasks: 1. Ask the user to enter the list of courses for Student A and Student B, separated by commas. 2. Convert each list into a set (to automatically remove duplicates). 3. Display: - The courses both students share (intersection). - The courses unique to each student (difference). - The total number of distinct courses offered between them (union).

For this starter, separate course names with a comma and one space. The string method split(", ") turns that text into a list of course names; set(...) removes duplicates. Complete the remaining reports using the operations above. Set display order may vary.

Code to complete:

a_courses = input("Enter Student A's courses (comma separated): ")
b_courses = input("Enter Student B's courses (comma separated): ")
a_courses = set(a_courses.split(", "))
b_courses = set(b_courses.split(", "))
# TODO: print the intersection, differences and union
Listing 183 — Mini Project — Course Enrollment Analyzer

Example Run:

Enter Student A's courses (comma separated): Math, Biology, History, English
Enter Student B's courses (comma separated): Math, Chemistry, English, Art

Shared courses: {'Math', 'English'}
Unique to Student A: {'Biology', 'History'}
Unique to Student B: {'Chemistry', 'Art'}
All distinct courses: {'Biology', 'Art', 'History', 'English', 'Chemistry', 'Math'}
Listing 184 — Mini Project — Course Enrollment Analyzer