← Previous

Lesson 15 · Python

Set

~30 min

1. Sets in Python

When working with collections of data in Python, you're already familiar with lists and tuples. But what happens when you need to store items where order doesn't matter, and duplicates are strictly forbidden? Enter sets! Sets are an essential data structure in Python designed specifically for handling unique items and performing mathematical set operations like unions and intersections at high speed.

Learning Objectives

  • Understand what a set is and when to use it over lists or dictionaries.
  • Create sets and automatically remove duplicate items from collections.
  • Add and remove elements using set methods like .add(), .remove(), and .discard().
  • Perform powerful set operations: Union, Intersection, Difference, and Symmetric Difference.

2. What is a Set?

A set in Python is an unordered, unindexed, and mutable collection of unique elements. You define a set by placing items inside curly braces {} separated by commas, or by using the built-in set() function.

Think of a set like a physical bag of lottery balls. The order of the balls inside the bag doesn't matter, you can't reach in to grab "ball number 0" by index, and you can never have two balls with the exact same identifier.

Python code example:

# Creating a set with curly braces
fruits = {"apple", "banana", "cherry"}

print(fruits)         # Output: {'apple', 'banana', 'cherry'} (order may vary!)
print(type(fruits))   # Output: <class 'set'>

# Sets automatically remove duplicates!
numbers = {1, 2, 2, 3, 4, 4, 4, 5}
print(numbers)        # Output: {1, 2, 3, 4, 5}

3. Unordered & Unindexed: What It Means

Because sets are unordered, their elements do not have a fixed position or index. This leads to two critical behaviors you must remember:

  • No indexing or slicing: Attempting to access an item with square brackets like my_set[0] will raise a TypeError.
  • Fast membership testing: Checking if an item exists inside a set using the in operator (e.g., "apple" in fruits) is blazingly fast—much faster than searching through a massive list.

Python code example:

usernames = {"admin", "developer", "tester"}

# Checking for existence is extremely fast
if "admin" in usernames:
    print("Access granted.")  # Output: Access granted.

# This WILL cause an error:
# print(usernames[0])  # TypeError: 'set' object is not subscriptable

4. Adding & Removing Set Elements

While set elements themselves must be immutable (like strings, numbers, or tuples), the set container itself is mutable. You can add new items or remove existing ones using built-in methods:

  • .add(item): Adds a single item to the set. If the item already exists, the set remains unchanged.
  • .remove(item): Removes an item. If the item is not found, Python raises a KeyError.
  • .discard(item): Safely removes an item. If the item is not found, it does nothing (no error!).
  • .clear(): Empties all elements from the set.

Python code example:

colors = {"red", "green"}

# Add an element
colors.add("blue")
print(colors)  # Output: {'red', 'green', 'blue'}

# Remove an element safely
colors.discard("yellow")  # No error, even though 'yellow' wasn't there!
colors.remove("red")      # Removes 'red'

print(colors)  # Output: {'green', 'blue'}

5. Mathematical Set Operations

Where sets really shine is in performing mathematical operations. Imagine you have two groups of data and you need to find overlap, combined items, or unique differences. Python provides both operators and methods for these:

Operation Operator Method Description
Union a | b a.union(b) All unique items from both sets.
Intersection a & b a.intersection(b) Only items present in BOTH sets.
Difference a - b a.difference(b) Items in `a` that are NOT in `b`.
Symmetric Difference a ^ b a.symmetric_difference(b) Items in either set, but NOT in both.

Python code example:

python_devs = {"Alice", "Bob", "Charlie"}
java_devs = {"Charlie", "David", "Alice"}

# 1. Union: Everyone who knows at least one language
all_devs = python_devs | java_devs
print(all_devs)  # Output: {'Alice', 'Bob', 'Charlie', 'David'}

# 2. Intersection: Full-stack devs who know BOTH languages
dual_devs = python_devs & java_devs
print(dual_devs)  # Output: {'Alice', 'Charlie'}

# 3. Difference: Devs who know Python but NOT Java
pure_python = python_devs - java_devs
print(pure_python)  # Output: {'Bob'}

6. Real World Example

Imagine you run an online learning platform and want to quickly remove duplicate email sign-ups from a newsletter list, then find out which students signed up for both Course A and Course B.

# Raw email signups containing accidental duplicates
raw_emails = ["sam@test.com", "alex@test.com", "sam@test.com", "jordan@test.com", "alex@test.com"]

# 1. Deduplicate instantly by converting the list to a set
unique_emails = set(raw_emails)
print(f"Unique subscribers count: {len(unique_emails)}")
# Output: Unique subscribers count: 3

# Course enrollment sets
course_a_students = {"sam@test.com", "alex@test.com", "taylor@test.com"}
course_b_students = {"jordan@test.com", "alex@test.com", "taylor@test.com"}

# 2. Find students enrolled in both courses
enrolled_in_both = course_a_students.intersection(course_b_students)
print("Students in both courses:", enrolled_in_both)
# Output: Students in both courses: {'alex@test.com', 'taylor@test.com'}

7. Common Beginner Mistakes

⚠️ Watch out for these mistakes:

  • Creating an Empty Set with {}: Writing empty_set = {} creates an empty dictionary, not a set! To create an empty set, you must use empty_set = set().
  • Attempting to Access Items by Index: Trying my_set[0] will fail with a TypeError because sets have no order or index.
  • Using .remove() on Missing Items: Using .remove() on an item that doesn't exist will crash your program with a KeyError. Use .discard() when you aren't sure if the item exists.
  • Storing Mutable Types Inside a Set: You cannot put lists or dictionaries inside a set (e.g., {[1, 2], [3, 4]}) because sets require all contained elements to be hashable (immutable).

8. Code Examples

Here are handy everyday patterns when working with Python sets:

# 1. One-liner list deduplication
my_list = [1, 2, 2, 3, 3, 3, 4]
clean_list = list(set(my_list))
print(clean_list)  # Output: [1, 2, 3, 4]

# 2. Iterating through a set
tags = {"python", "coding", "tutorial"}
for tag in tags:
    print(f"Tag: #{tag}")

# 3. Checking for sub-sets and super-sets
small_set = {1, 2}
big_set = {1, 2, 3, 4, 5}

print(small_set.issubset(big_set))    # Output: True
print(big_set.issuperset(small_set))  # Output: True
Interactive Practice

Mini Practice: Unique Tag Manager

Create a set named my_tags with duplicate string entries (e.g., "python", "code", "python", "tech"). Add a new tag "web" using .add(), then print the set and its total count using len().

0% complete
Check when done
Quiz

Test Your Understanding

1. How do Python sets handle duplicate values when created?

2. What is the correct way to initialize an EMPTY set in Python?

3. Which set method removes an element WITHOUT raising an error if the item does not exist?

4. What is the result of using the intersection operator `set1 & set2`?

9. Challenge Project

Event Attendance Analyzer: Imagine you are organizing a developer conference. Create two sets representing attendees on day_1 = {"Alice", "Bob", "Charlie", "David"} and day_2 = {"Charlie", "David", "Eve", "Frank"}. Write a Python script that calculates and prints:

  • The total list of unique people who attended the conference overall (Union).
  • The dedicated attendees who came on both days (Intersection).
  • The attendees who came only on Day 1 (Difference).

10. Key Takeaways

  • Sets are unordered collections of unique elements.
  • Duplicates are automatically removed upon creation or insertion.
  • Use set() to create an empty set (because {} creates an empty dictionary).
  • Sets do not support indexing or slicing (my_set[0] causes an error).
  • Use Union (|), Intersection (&), and Difference (-) to perform fast data analysis.

🚀 Progression

You've mastered Python sets! Next up, we will bring together all data structures in the upcoming lesson on **Dictionaries in Python**!