Sets are unordered collections of unique items. They are useful for membership testing, removing duplicates, and performing mathematical set operations.
1) What is a Set?
A set is an unordered collection of unique elements enclosed in curly braces { } or created using set().
Sets do not allow duplicates and do not maintain order.
# Examples
empty_set = set() # Note: {} creates an empty dictionary
numbers = {1, 2, 3, 4}
fruits = {"apple", "banana", "cherry"}
mixed = {1, "Alice", True}
2) Accessing Elements
Since sets are unordered, elements cannot be accessed by index. You can iterate through sets:
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
3) Adding and Removing Elements
fruits = {"apple", "banana"}
# Adding
fruits.add("cherry")
fruits.update(["mango", "kiwi"]) # Add multiple items
# Removing
fruits.remove("banana") # Raises KeyError if item not found
fruits.discard("orange") # Does not raise error if item not found
popped_item = fruits.pop() # Removes a random item
fruits.clear() # Remove all items
4) Set Operations
Python sets support mathematical operations like union, intersection, difference, and symmetric difference:
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Union: {1, 2, 3, 4, 5, 6}
print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}
print(a ^ b) # Symmetric Difference: {1, 2, 5, 6}
5) Common Set Methods
add(x)– Add an elementupdate(iterable)– Add multiple elementsremove(x)– Remove element (KeyError if missing)discard(x)– Remove element safelypop()– Remove a random elementclear()– Remove all elementsunion(), intersection(), difference(), symmetric_difference()– Mathematical operations
6) Common Mistakes
- Using mutable elements like lists inside sets →
TypeError - Expecting order → sets are unordered
- Accessing by index → not allowed
No comments:
Post a Comment