Python has a set of built-in methods that you can use on sets.
Example
Add an element to the fruits set:
fruits = {“apple”, “banana”, “cherry”}
fruits.add(“orange”)
print(fruits)
Output:
{‘orange’, ‘banana’, ‘cherry’, ‘apple’}
| Method | Syntax | Description |
|---|---|---|
| add() | set.add(elmnt) | Adds an element to the set |
| clear() | set.clear() | Removes all the elements from the set |
| copy() | set.copy() | Returns a copy of the set |
| difference() | set.difference(set) | Returns a set containing the difference between two or more sets |
| difference_update() | set.difference_update(set) | Removes the items in this set that are also included in another, specified set |
| discard() | set.discard(value) | Remove the specified item |
| intersection() | set.intersection(set1, set2 … etc) | Returns a set, that is the intersection of two other sets |
| intersection_update() | set.intersection_update(set1, set2 … etc) | Removes the items in this set that are not present in other, specified set(s) |
| isdisjoint() | set.isdisjoint(set) | Returns whether two sets have a intersection or not |
| issubset() | set.issubset(set) | Returns whether another set contains this set or not |
| issuperset() | set.issuperset(set) | Returns whether this set contains another set or not |
| pop() | set.pop() | Removes an element from the set |
| remove() | set.remove(item) | Removes the specified element |
| symmetric_difference() | set.symmetric_difference(set) | Returns a set with the symmetric differences of two sets |
| symmetric_difference_update() | set.symmetric_difference_update(set) | inserts the symmetric differences from this set and another |
| union() | set.union(set1, set2…) | Return a set containing the union of sets |
| update() | set.update(set) | Update the set with the union of this set and others |
