Python set methods are built-in functions that allow you to perform various operations on sets, which are unordered collections of unique elements. These methods support common set operations like union, intersection, difference, and membership checks.
Core Set Methods
add(element): Adds a single element to the set. If the element already exists, the set remains unchanged.remove(element): Removes a specified element. Raises aKeyErrorif the element is not found.discard(element): Removes a specified element if it exists; does nothing if the element is not in the set.pop(): Removes and returns an arbitrary element from the set. Raises aKeyErrorif the set is empty.clear(): Removes all elements from the set, making it empty.copy(): Returns a shallow copy of the set.
Set Operations
union(*others): Returns a new set with all elements from the set and all other sets. Can be written asset1 | set2.intersection(*others): Returns a new set with elements common to all sets. Can be written asset1 & set2.difference(*others): Returns a new set with elements in the set but not in any of the others. Can be written asset1 - set2.symmetric_difference(other): Returns a new set with elements in either set but not in both. Can be written asset1 ^ set2.
Update Methods (Modify in Place)
update(*others): Adds elements from other sets or iterables to the set.intersection_update(*others): Updates the set with the intersection of itself and other sets.difference_update(*others): Updates the set with the difference between itself and other sets.symmetric_difference_update(other): Updates the set with the symmetric difference of itself and another set.
Comparison Methods
issubset(other): ReturnsTrueif all elements of the set are inother.issuperset(other): ReturnsTrueif all elements ofotherare in the set.isdisjoint(other): ReturnsTrueif the set andotherhave no elements in common.
These methods are essential for efficient data manipulation, especially when handling unique values or performing mathematical set operations.