iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Set Methods

Set methods reference. Most set operations have both a method form and an operator form — they're equivalent.

Add & remove

MethodWhat it does
add(x)Add an element.
update(iter)Add many at once.
remove(x)Remove x; KeyError if missing.
discard(x)Remove x; do nothing if missing.
pop()Remove and return arbitrary element.
clear()Empty.

Set algebra

MethodOperatorReturns
union(other)a \| bAll elements in either.
intersection(other)a & bIn both.
difference(other)a - bIn a, not in b.
symmetric_difference(other)a ^ bIn one, not both.
issubset(other)a <= bTrue if a is a subset.
issuperset(other)a >= bTrue if a contains b.
isdisjoint(other)True if no common elements.

In-place

Each set-algebra method has an *_update in-place version: intersection_update, difference_update, symmetric_difference_update. Operators have &= -= ^= |=.

Membership is O(1)

PYTHON
banned = {'spam', 'phish', 'noreply'}

if user in banned:
    reject()

frozenset

An immutable set — hashable, so it can be used as a dict key or a member of another set. Build with frozenset(iter).

Tip: Sets dedup but don't preserve order. For order-preserving dedup use list(dict.fromkeys(items)).

Example

Example
a = {1, 2, 3}
b = {2, 3, 4}
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
print(a.issubset({1, 2, 3, 4}))
Try it Yourself »

Exercise

Remove an element without raising if absent.

s. (x)

Test yourself

Q1. a - b returns…
Q2. Safe-remove (no error if missing) is…
Q3. Test "no common elements" with…

Discussion

Loading…