Python Lesson 14: Sets

🐍 Python CourseLesson 14 of 26 · 54% complete

A set stores unique values — no duplicates allowed. Sets are fast for checking membership and performing set math (union, intersection, difference).

Creating Sets

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

# Create from a list (removes duplicates!)
numbers = set([1, 2, 2, 3, 3, 3, 4])
print(numbers)  # {1, 2, 3, 4} — duplicates gone!

# Empty set
empty = set()  # NOT {} — that creates a dict!

Set Operations

a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}

print(a | b)    # Union: {1,2,3,4,5,6,7,8}
print(a & b)    # Intersection: {4, 5}
print(a - b)    # Difference: {1, 2, 3}
print(a ^ b)    # Symmetric diff: {1,2,3,6,7,8}

Modifying Sets

fruits = {"apple", "banana"}

fruits.add("cherry")      # add one item
fruits.update(["date", "elderberry"])  # add many
fruits.remove("banana")   # remove (error if missing)
fruits.discard("grape")   # remove (no error if missing)

print("apple" in fruits)  # True — fast membership check!

When to Use Sets

# Remove duplicates from a list
visitors = ["alice", "bob", "alice", "charlie", "bob"]
unique = list(set(visitors))
print(unique)  # ["alice", "bob", "charlie"]

# Fast membership check (faster than list!)
blocked_users = {"spam1", "spam2", "baduser"}
if "spam1" in blocked_users:
    print("Blocked!")

🏋️ Practice Task

You have two lists of students who attended class: monday = [“Alice”,”Bob”,”Charlie”,”Alice”] and tuesday = [“Bob”,”Charlie”,”David”]. Find: (1) unique students total, (2) who attended both days, (3) who only attended Monday.

💡 Hint: Convert to sets. Use set | set for union, set & set for intersection, set – set for difference.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *