► Understanding Sets
Sets are unordered collections of unique elements. They automatically remove duplicates and are perfect for membership testing, removing duplicates, and mathematical set operations.
► Real-World Analogy
Think of sets like a bag of unique marbles:
» If you try to add a marble that’s already in the bag, nothing happens
» You can’t have two identical marbles (no duplicates)
» The order doesn’t matter – you just have a collection of unique items
» You can combine bags (union) or find common marbles (intersection)
» Perfect for answering “Is this marble in the bag?”
► Key Concepts
✓ Unique elements: No duplicates allowed
✓ Unordered: Items have no specific position
✓ Mutable: Can add/remove elements
✓ Fast membership testing: O(1) average time
✓ Mathematical operations: union, intersection, difference
■ Code Examples
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# Creating sets fruits = {"apple", "banana", "orange"} numbers = {1, 2, 3, 4, 5} mixed = {"hello", 42, True} print(fruits) # Removing duplicates with_duplicates = [1, 2, 2, 3, 3, 3, 4] unique = set(with_duplicates) print(f"Unique: {unique}") # Adding and removing fruits.add("mango") fruits.remove("banana") print(f"Modified: {fruits}") # Set operations set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6} print(f"Union: {set1 | set2}") print(f"Intersection: {set1 & set2}") print(f"Difference: {set1 - set2}") # Membership testing print(f"Is 3 in set1? {3 in set1}") print(f"Is 10 in set1? {10 in set1}") |
