Table B.10 outlines the various operators, (built-in and factory) functions, and built-in methods that apply to both set types (set [mutable] and frozenset [immutable]).
Table B.10. Set Type Operators, Functions, and Methods
Function/Method Name | Operator Equivalent | Description |
---|
All Set Types |
len(s) | | Set cardinality: number of elements in s |
set([obj]) | | Mutable set factory function; if obj given, it must be iterable, new set elements taken from obj; if not, creates an empty set |
frozenset ([obj]) | | Immutable set factory function; operates the same as set() except returns immutable set |
| obj in s | Membership test: is obj an element of s? |
| obj not in s | Non-membership test: is obj not an element of s? |
| s == t | Equality test: do s and t have exactly the same elements? |
| s != t | Inequality test: opposite of == |
| s < t | (Strict) subset test; s !=t and all elements of s are members of t |
s.issubset(t) | s <= t | Subset test (allows improper subsets): all elements of s are members of t |
| s > t | (Strict) superset test: s != t and all elements of t are members of s |
s.issuperset(t) | s >= t | Superset test (allows improper supersets): all elements of t are members of s |
s.union(t) | s | t | Union operation: elements in s or t |
s.intersection(t) | s & t | Intersection operation: elements in s and t |
s.difference(t) | s - t | Difference operation: elements in s that are not elements of t |
s.symmetric_difference(t) | s ^ t | Symmetric difference operation: elements of either s or t but not both |
s.copy() | | Copy operation: return (shallow) copy of s |
Mutable Sets Only |
s.update(t) | s |= t | (Union) update operation: members of t added to s |
s.intersection_update(t) | s &= t | Intersection update operation: s only contains members of the original s and t |
s.difference_update(t) | s -= t | Difference update operation: s only contains original members who are not in t |
s.symmetric_difference_update(t) | s ^= t | Symmetric difference update operation: s only contains members of s or t but not both |
s.add(obj) | | Add operation: add obj to s |
s.remove(obj) | | Remove operation: remove obj from s; Key-Error raised if obj not in s |
s.discard(obj) | | Discard operation: friendlier version of remove()remove obj from s if obj in s |
s.pop() | | Pop operation: remove and return an arbitrary element of s |
s.clear() | | Clear operation: remove all elements of s |