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"}
[Link]("orange") # {"apple", "banana", "orange"}
[Link]("banana") # {"apple", "orange"}
[Link]("mango") # No error if "mango" not in set
[Link]() # Removes a random element
[Link]() # 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([Link](set2)) # {1, 2, 3, 4, 5}
print([Link](set2)) # {3}
print([Link](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])
# [Link](4) # Error: Cannot modify a frozenset