What You Will Learn
Beginner
- What sets are and when to use them
- Set operations (union, intersection, difference)
- Removing duplicates
Terminalpython
# Creating sets
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 2, 3, 3, 3]) # {1, 2, 3} - removes duplicates!
# Add and remove
fruits.add("date")
fruits.remove("banana") # Raises KeyError if not found
fruits.discard("grape") # Safe removal (no error if missing)
# Check membership (very fast!)
print("apple" in fruits) # True
# Length (count of unique items)
print(len(fruits))Set Operations
Terminalpython
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# Union (all unique items)
print(a | b) # {1, 2, 3, 4, 5, 6}
print(a.union(b)) # same
# Intersection (common items)
print(a & b) # {3, 4}
print(a.intersection(b)) # same
# Difference (in a but not in b)
print(a - b) # {1, 2}
print(a.difference(b)) # same
# Symmetric difference (in one, not both)
print(a ^ b) # {1, 2, 5, 6}Remove duplicates from a list
list(set(my_list)) - the fastest way to remove duplicates. But order is lost. Use dict.fromkeys() to preserve order.Practical Exercise
Create a set from [1, 1, 2, 2, 3, 3] - duplicates removed!
Union: {1,2,3} | {3,4,5}
Intersection: {1,2,3} & {2,3,4}
Difference: {1,2,3} - {2,3,4}
Key Takeaways
- Sets store unique items only - no duplicates.
- Create from list: set([1,1,2]) = {1,2}.
- Operations: | (union), & (intersection), - (difference), ^ (symmetric).
- discard() removes safely (no KeyError).
- in check is O(1) - very fast for large collections.
Comments
Comments
Post a Comment