Table of Contents » Reference Materials : Set Methods
Set Methods
Python sets are collections of unique elements, and their methods provide powerful ways to handle and manipulate these collections. Key methods include add(element) for adding a single element, and update([elements]) for adding multiple elements. To remove elements, remove(element) deletes an element and raises an error if it doesn't exist, whereas discard(element) deletes an element without raising an error. The pop() method removes and returns an arbitrary set element. Sets can be combined using union() or the | operator, and their intersection is found using intersection() or the & operator. Similarly, difference() or - and symmetric_difference() or ^ are used to find unique elements in sets. Sets also have methods like issubset() and issuperset() to compare sets. These methods make Python sets a robust and versatile tool for handling unique collections, enabling efficient operations for mathematical set-like computations and more.
Set Method | Description |
---|---|
add() |
Adds an element to the specified set.
|
clear() |
Removes all elements from the specified set.
|
copy() |
Returns a copy of the specified set.
|
difference() |
Returns a set containing the difference between two or more specified sets.
|
difference_update() |
Removes the items from one specified set that are also included in another specified set.
|
discard() |
Removes the specified item from the specified set.
|
intersection() |
Returns a set that is the intersection of two or more specified sets.
|
intersection_update() |
Removes items from a specified set that are not in another specified set.
|
isdisjoint() |
Returns True or False whether two specified sets have an intersection or not.
|
issubset() |
Returns True or False whether a specified set contains another specified set.
|
issuperset() |
Returns True or False whether a specified set contains another specified set.
|
pop() |
Removes an element from the specified set.
|
remove() |
Removes a specified element from a specified set.
|
symmetric_difference() |
Returns a set of values that are the symmetric difference between two specified sets.
|
symmetric_difference_update() |
Inserts the symmetric differences from a specified set into another specified set.
|
union() |
Returns a set containing the union of one or more specified sets.
|
update() |
Updates the specified set with another specified set, or any other specified iterable.
|