set#

set is a mutable, unordered collection of unique hashable values. in and add / remove are O(1) average. The right container for membership tests, deduplication, and set algebra.

Daily kit on set. Examples assume xs = {1, 2, 3}.

Operation

Example

Effect

Literal

{1, 2, 3}

Standard set literal.

From iterable

set([1, 2, 2, 3])

{1, 2, 3}; duplicates collapse.

Empty

set()

Empty set; {} is a dict.

add

xs.add(4)

Insert (no-op if already present).

discard

xs.discard(99)

Remove if present; silent on miss.

remove

xs.remove(1)

Remove; KeyError if missing.

pop

xs.pop()

Remove and return an arbitrary element.

Set algebra with the bitwise operators. Examples assume a = {1, 2, 3} and b = {2, 3, 4}.

Operation

Example

Result

Union

a | b

{1, 2, 3, 4}

Intersection

a & b

{2, 3}

Difference

a - b

{1}

Symmetric difference

a ^ b

{1, 4}

Subset

a <= b

False (every element of a in b)

Superset

a >= b

False (every element of b in a)

Idiomatic uses, one per block.

Membership against a small fixed set, cleaner than chained ==.

if x in {1, 2, 3}:
    ...

De-duplicate any iterable.

uniques = set(xs)

Find required keys absent from a presence set.

missing = required - present

Only hashable values fit in a set. list and dict are not hashable; use tuple and frozenset when nesting is needed.

Method catalog#

The full instance-method surface on set. Every set-algebra method also has an operator form; the methods accept any iterable, the operators require a set on both sides.

Mutators#

Method

Effect

add(x)

Insert (no-op if already present).

discard(x)

Remove if present; silent on miss.

remove(x)

Remove; KeyError if missing.

pop()

Remove and return an arbitrary element.

clear()

Drop every element.

update(*others)

In-place union with iterables.

intersection_update(*others)

In-place intersection.

difference_update(*others)

In-place difference.

symmetric_difference_update(other)

In-place symmetric difference.

Set algebra (return a new set)#

Method

Equivalent

union(*others)

a | b | c

intersection(*others)

a & b & c

difference(*others)

a - b - c

symmetric_difference(other)

a ^ b

copy()

Shallow copy.

Predicates#

Method

True when

isdisjoint(other)

No common elements.

issubset(other)

Every element is in other.

issuperset(other)

Every element of other is in self.

add and discard mutate the set in place.

xs = {1, 2}; xs.add(3); xs.discard(99); xs
{1, 2, 3}

update is in-place union with any iterable.

xs = {1, 2}; xs.update([2, 3, 4]); xs
{1, 2, 3, 4}

isdisjoint is the cheap “no overlap?” check.

{1, 2}.isdisjoint({3, 4}), {1, 2}.isdisjoint({2, 3})
(True, False)

issubset mirrors the <= operator.

{1, 2}.issubset({1, 2, 3})
True

Operator overloading#

set implements the set-algebra dunders.

Operator

Dunder

Returns

a | b

__or__

Union.

a & b

__and__

Intersection.

a - b

__sub__

Difference.

a ^ b

__xor__

Symmetric difference.

a |= b

__ior__

In-place union.

a &= b

__iand__

In-place intersection.

a -= b

__isub__

In-place difference.

a ^= b

__ixor__

In-place symmetric difference.

a <= b

__le__

Subset test.

a < b

__lt__

Proper subset test.

a == b

__eq__

Equality.

x in a

__contains__

Membership.

len(a)

__len__

Cardinality.

iter(a)

__iter__

Iteration (unordered).

bool(a)

__bool__

False only for the empty set.

Set algebra reads naturally with the bitwise operators.

{1, 2, 3} | {3, 4}, {1, 2, 3} & {3, 4}, {1, 2, 3} - {3, 4}
({1, 2, 3, 4}, {3}, {1, 2})

A class that wraps a set can forward __or__ / __contains__ to behave like a set in expressions.

class TagSet:
    def __init__(self, tags=()): self.tags = set(tags)
    def __or__(self, other): return TagSet(self.tags | other.tags)
    def __contains__(self, t): return t in self.tags
    def __repr__(self): return f"TagSet({self.tags})"

"admin" in TagSet({"user", "admin"})
True

References#