Chapter 6: Data Structures / Lesson 39

Sets

Introduction to Sets

Sets are unordered collections of unique elements. Unlike lists, sets don't allow duplicate values and don't maintain order. Sets are perfect for membership testing, removing duplicates, and mathematical set operations.

Sets are mutable (you can add/remove items), but the items themselves must be immutable (like strings, numbers, or tuples).

Creating Sets

Sets are created using curly braces {} or the set() function:

creating_sets.py
# Using curly braces fruits = {"apple", "banana", "cherry"} # Using set() function numbers = set([1, 2, 3, 3, 2]) # Duplicates removed print(numbers) # {1, 2, 3} # Empty set (must use set(), not {}) empty = set() # Remove duplicates from list my_list = [1, 2, 2, 3, 3, 3] unique = list(set(my_list)) print(unique) # [1, 2, 3]

Set Operations

Sets support mathematical set operations:

set_operations.py
set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6} # Union (all elements from both sets) union = set1 | set2 # or set1.union(set2) print(union) # {1, 2, 3, 4, 5, 6} # Intersection (common elements) intersection = set1 & set2 # or set1.intersection(set2) print(intersection) # {3, 4} # Difference (elements in set1 but not in set2) difference = set1 - set2 # or set1.difference(set2) print(difference) # {1, 2} # Symmetric difference (elements in either set, but not both) sym_diff = set1 ^ set2 # or set1.symmetric_difference(set2) print(sym_diff) # {1, 2, 5, 6}

Set Methods

Common methods for working with sets:

set_methods.py
fruits = {"apple", "banana"} # add() - add single item fruits.add("cherry") # update() - add multiple items fruits.update(["orange", "grape"]) # remove() - remove item (raises error if not found) fruits.remove("banana") # discard() - remove item (no error if not found) fruits.discard("mango") # pop() - remove and return arbitrary item item = fruits.pop() # clear() - remove all items fruits.clear() # Membership testing if "apple" in fruits: print("Apple is in the set")

When to Use Sets

✅ Use Sets When:

• You need unique values (no duplicates)

• Fast membership testing is important

• You need set operations (union, intersection, etc.)

• Order doesn't matter

💡 Important Notes

• Sets are unordered (order may vary)

• Sets cannot contain mutable items (like lists)

• Sets are faster than lists for membership testing

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...