Set Operations
Python provides a variety of operations applicable to sets. Since sets are containers, the built-in len function can take a set as its single argument and return the number of items in the set object. A set is iterable, so you can pass it to any function or method that takes an iterable argument. In this case, the items of the set are iterated upon, in some arbitrary order. For example, for any set S, min(S) returns the smallest item in S.
Set Membership
The k in S operator checks whether object k is one of the items of set S. It returns True if it is and False if it isn’t. Similarly, k not in S is just like not (k in S).
Set Methods
Set objects provide several methods, as shown in Table 4-4. Nonmutating methods return a result without altering the object to which they apply and can also be called on instances of type frozenset, while mutating methods may alter the object to which they apply and can be called only on instances of type set. In Table 4-4, S and S1 indicate any set object, and x any hashable object.
Table 4-4. Set object methods
Method | Description |
|---|---|
Nonmutating methods | |
| Returns a shallow copy of the set (a copy whose items are the same objects as |
| Returns the set of all items of |
| Returns the set of all items of |
| Returns |
| Returns |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access