Reference to Python Set Methods
Python provides a variety of built-in methods designed specifically for sets. These methods, sometimes called set functions, depend entirely on their parent class. We can use these methods whenever set operations are needed. This tutorial lists all the built-in set methods in alphabetical order, serving as a comprehensive and up-to-date reference for developers.
Alphabetical Reference
The table below lists all 17 Python set methods arranged in alphabetical order for easy reference.
Method | Description |
---|---|
add() | Adds a single element to the set if it is not already present. |
clear() | Removes all elements from the set, leaving it empty. |
copy() | Creates a shallow copy of the set and returns it. |
difference() | Returns a new set containing elements present in the current set but not in others. |
difference_update() | Removes elements found in other sets from the current set in place. |
discard() | Removes a specific element from the set if it exists, without raising an error. |
intersection() | Returns a new set with elements common to the current set and all others provided. |
intersection_update() | Updates the current set, keeping only elements found in all specified sets. |
isdisjoint() | Returns True if the set has no elements in common with another set. |
issubset() | Returns True if all elements of the set are contained in another set. |
issuperset() | Returns True if the set contains all elements of another set. |
pop() | Removes and returns an arbitrary element from the set. |
remove() | Removes a specific element from the set; raises an error if not found. |
symmetric_difference() | Returns a new set with elements in either set but not in both. |
symmetric_difference_update() | Updates the set by keeping only elements unique to either set. |
union() | Returns a new set containing all elements from the current and other sets. |
update() | Adds elements from another set or iterable to the current set. |
Dynamically Get Python Set Methods
The Python language pack contains all the built-in methods to apply on sets and fortunately, we can retrieve that list dynamically from the distribution. Use the following code to acquire the up-to-date and ultimate list of Python set methods.
Get Python Set Methods
# Get the list of set methods set_methods = [ method for method in dir(set) if callable(getattr(set, method)) and not method.startswith('__') ] # Print the list of set methods print(set_methods)