Python 3 reference · 17 entries

Python Set Methods

Every Python set method: add and remove elements, and combine sets with union, intersection and difference, with runnable examples.

Sets hold unique, hashable items with fast membership tests. Most methods also have an operator form (|, &, -, ^).

NameDescriptionSince
set.add() Add one element to the set. Adding an element that is already present does nothing. 3.0
set.clear() Remove every element from the set in place, leaving an empty set. Other references to the set see the change. 3.0
set.copy() Return a shallow copy of the set: a new set with the same elements, which you can change without affecting the original. 3.0
set.difference() Return a new set with the elements of this set that are not in the others. The same as a - b. 3.0
set.difference_update() Remove from this set every element found in the others, in place. The same as a -= b. 3.0
set.discard() Remove an element if it is present; do nothing if it isn't. The no-error version of remove(). 3.0
set.intersection() Return a new set with the elements common to this set and all others. The same as a & b. 3.0
set.intersection_update() Keep only the elements found in this set and all others, in place. The same as a &= b. 3.0
set.isdisjoint() Return True if the set has no elements in common with another iterable. 3.0
set.issubset() Return True if every element of this set is also in the other. The same as a <= b. 3.0
set.issuperset() Return True if this set contains every element of the other. The same as a >= b. 3.0
set.pop() Remove and return an arbitrary element of the set. Raises KeyError if the set is empty. 3.0
set.remove() Remove an element from the set. Raises KeyError if it isn't present; use discard() to avoid the error. 3.0
set.symmetric_difference() Return a new set with elements in either set but not both. The same as a ^ b. 3.0
set.symmetric_difference_update() Update the set in place to keep elements in either set but not both. The same as a ^= b. 3.0
set.union() Return a new set with all elements from this set and the others. The same as a | b. 3.0
set.update() Add all elements from one or more iterables to the set, in place. The same as a |= b. 3.0