Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Sets & Set Operations
Sets are unordered collections of unique elements. They support mathematical set operations - union, intersection, difference. Use them to remove duplicates and check membership efficiently.
Sets
# Creating sets
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 4, 5}
from_list = set([1, 2, 2, 3, 3, 3])
print(from_list) # {1, 2, 3} (duplicates removed!)
# Adding & removing
fruits.add("date")
fruits.discard("banana") # no error if missing
# fruits.remove("mango") # KeyError if missing!
# 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 difference: {1, 2, 3, 6, 7, 8}
# Membership (very fast! O(1))
print(3 in a) # True
print(10 in a) # False
# Practical: remove duplicates
names = ["Alice", "Bob", "Alice", "Charlie", "Bob"]
unique = list(set(names))
print(unique)
# Set comprehension
squares = {x**2 for x in range(10)}
print(squares)Tip
Tip
Sets have O(1) lookup - checking 'if x in my_set' is instant regardless of size. Use sets for membership testing over lists.
List for mutable sequences, tuple for immutable data, set for unique items
Common Mistake
Warning
Sets are unordered - you can't index them (no my_set[0]). Convert to list first if you need indexing. Also {} creates an empty dict, not set. Use set().
Practice Task
Note
(1) Remove duplicates from a list using set(). (2) Find common elements between two sets. (3) Find items in set A but not in B. (4) Use set comprehension.