Set methods · Python Reference

Sets store unique items and make membership tests fast. Their methods add and remove items and combine sets with union, intersection and difference. Each page gives the syntax, the return value, a runnable example and a note on the common mistakes, such as expecting order.

All 11

Python Set add() Method
`set.add(element)` inserts **one** element into a set in place and returns `None`. If the element is already in the set, nothing …
Python Set remove() Method
`set.remove(element)` deletes the element from the set in place and returns `None`. If the element is **not** in the set it raise…
Python Set discard() Method
`set.discard(element)` removes the element from the set if it is present and does nothing if it is not. It always returns `None` …
Python Set pop() Method
`set.pop()` removes one **arbitrary** element from the set and returns it. On an empty set it raises `KeyError`.
Python Set union() Method
`a.union(b)` returns a **new** set containing every element that is in `a`, in `b`, or in both. The original sets are not changed.
Python Set intersection() Method
`a.intersection(b)` returns a **new** set with only the elements that appear in both `a` and `b`. The original sets are unchanged.
Python Set difference() Method
`a.difference(b)` returns a **new** set of the elements that are in `a` but **not** in `b`. The order of the sets matters, and th…
Python Set symmetric_difference() Method
`a.symmetric_difference(b)` returns a **new** set of elements that are in `a` or in `b` but **not in both**. It is the same as `a…
Python Set update() Method
`set.update(*iterables)` adds every item of each iterable into the set **in place** and returns `None`. Duplicates are ignored.
Python Set issubset() Method
`a.issubset(b)` returns `True` if **every** element of `a` is also in `b`, otherwise `False`. It is the same test as `a <= b`.
Python Set clear() Method
`set.clear()` removes **all** elements from the set in place and returns `None`. The set object still exists afterwards, but it i…

Explore more

Python ProgramsPython ComparisonsPython How-To GuidesPython Cheat SheetsPython glossaryPython tutorial