Important Set Methods in Python
1. Adding & Removing Elements
- add(element): Adds an element to the set.
- remove(element): Removes an element; raises KeyError if not found.
- discard(element): Removes an element if present, without error if absent.
- pop(): Removes and returns a random element (sets are unordered).
- clear(): Removes all elements from the set.
Example:
fruits = {"apple", "banana"}
fruits.add("orange") # {"apple", "banana", "orange"}
fruits.remove("banana") # {"apple", "orange"}
fruits.discard("mango") # No error if "mango" not in set
fruits.pop() # Removes a random element
fruits.clear() # Empty set
2. Set Operations (Union, Intersection, Difference)
- union(other_set): Returns a new set with all elements from both sets.
- intersection(other_set): Returns a set with common elements.
- difference(other_set): Returns a set with elements in the first set but not in the second.
- symmetric_difference(other_set): Returns elements in either set, but not in both.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # {3}
print(set1.difference(set2)) # {1, 2}
print(set1.symmetric_difference(set2)) # {1, 2, 4, 5}
3. Updating Sets (In-Place Operations)
- update(other_set): Adds elements from another set.
- intersection_update(other_set): Keeps only elements found in both sets.
- difference_update(other_set): Removes elements found in another set.
- symmetric_difference_update(other_set): Keeps elements found in either set but not in both.
4. Subset, Superset, and Disjoint Checks
- issubset(other_set): Checks if the set is a subset of another set.
- issuperset(other_set): Checks if the set is a superset of another set.
- isdisjoint(other_set): Checks if two sets have no common elements.
5. Copying a Set
- copy(): Returns a shallow copy of the set.
6. Frozenset (Immutable Set)
- frozenset(iterable): Creates an immutable version of a set.
- Supports all read-only set methods like union, intersection, etc.
Example:
frozen = frozenset([1, 2, 3])
# frozen.add(4) # Error: Cannot modify a frozenset