Python set methods
Unique items and set maths: add, discard, union, intersection, difference and more.
A set holds each value only once and has no order. Set methods add and remove items and combine sets the way you did in school maths: union (everything), intersection (only what both have) and difference (what one has and the other does not).
All 13 set methods
- set.add()Puts one element into a set. If the element is already there, nothing happens: a set never holds duplicates.
- set.clear()Empties a set in place, leaving set(). Every variable that refers to the same set sees it empty afterwards.
- set.difference()Returns a new set with the elements of this set that are not in any of the others. Same as the - operator.
- set.discard()Removes an element from a set if it is there, and silently does nothing if it is not. It never raises an error.
- set.intersection()Returns a new set with only the elements that appear in this set and in every other one given. Same as the & operator.
- set.isdisjoint()Returns True when this set and the other collection have no element in common, and False as soon as one is shared.
- set.issubset()Returns True when every element of this set is also in the other collection. Same as the <= operator for two sets.
- set.issuperset()Returns True when this set contains every element of the other collection. Same as the >= operator for two sets.
- set.pop()Removes one element from a set and returns it. You cannot choose which: sets have no order, so treat it as arbitrary.
- set.remove()Deletes an element from a set. Raises KeyError if the element is not in the set; use discard() to skip that check.
- set.symmetric_difference()Returns a new set with the elements that are in exactly one of the two sets, never in both. Same as the ^ operator.
- set.union()Returns a new set with every element that is in this set or in any of the others, each one only once. Same as the | operator.
- set.update()Adds every element from one or more lists, sets or other iterables into the set, in place. Duplicates are ignored.