Operation | Result | Example |
len(s) | cardinality (size) of set s |
s = { 2, 3, 2, 4, 3 }
print(len(s))
|
s.copy() | new set with a shallow copy of s |
s = { 1, 2, 3 }
t = s.copy()
s.add(4)
print(s)
print(t)
|
s.clear() | remove all elements from set s |
s = { 1, 2, 3 }
s.clear()
print(s, len(s))
|
Operation | Result | Example |
x in s | test x for membership in s |
s = { 1, 2, 3 }
print(0 in s)
print(1 in s)
|
x not in s | test x for non-membership in s |
s = { 1, 2, 3 }
print(0 not in s)
print(1 not in s)
|
s.add(x) | add element x to set s |
s = { 1, 2, 3 }
print(s, 4 in s)
s.add(4)
print(s, 4 in s)
|
s.remove(x) | remove x from set s; raises KeyError if not present |
s = { 1, 2, 3 }
print(s, 3 in s)
s.remove(3)
print(s, 3 in s)
s.remove(3) # crashes
|
s.discard(x) | removes x from set s if present |
s = { 1, 2, 3 }
print(s, 3 in s)
s.discard(3)
print(s, 3 in s)
s.discard(3) # does not crash!
print(s, 3 in s)
|
Operation | Equivalent | Result | Example |
s.issubset(t) | s <= t | test whether every element in s is in t |
print({1,2} <= {1}, {1,2}.issubset({1}))
print({1,2} <= {1,2}, {1,2}.issubset({1,2}))
print({1,2} <= {1,2,3}, {1,2}.issubset({1,2,3}))
|
s.issuperset(t) | s >= t | test whether every element in t is in s |
print({1,2} >= {1}, {1,2}.issuperset({1}))
print({1,2} >= {1,2}, {1,2}.issuperset({1,2}))
print({1,2} >= {1,2,3}, {1,2}.issuperset({1,2,3}))
|
s.union(t) | s | t | new set with elements from both s and t |
print({1,2} | {1}, {1,2}.union({1}))
print({1,2} | {1,3}, {1,2}.union({1,3}))
s = {1,2}
t = s | {1,3}
print(s, t)
|
s.intersection(t) | s & t | new set with elements common to s and t |
print({1,2} & {1}, {1,2}.intersection({1}))
print({1,2} & {1,3}, {1,2}.intersection({1,3}))
s = {1,2}
t = s & {1,3}
print(s, t)
|
s.difference(t) | s - t | new set with elements in s but not in t |
print({1,2} - {1}, {1,2}.difference({1}))
print({1,2} - {1,3}, {1,2}.difference({1,3}))
s = {1,2}
t = s - {1,3}
print(s, t)
|
s.update(t) | s |= t | modify s adding all elements found in t |
s = {1,2}
t = {1,3}
u = {2,3}
s.update(u)
t |= u
print(s, t, u)
|