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
Table 4-4. Set object methods (continued)
All mutating methods of set objects, except pop, return None. The pop method can be used for destructive iteration on a set, consuming little extra memory. The memory savings make pop usable for a loop on a huge set, when what you want is to "consume" the set in the course of the loop. Sets also have mutating methods named difference_update, intersection_update, symmetric_difference_update, and update (corresponding to nonmutating method union). Each such mutating method performs the same operation as the corresponding nonmutating method, but it performs the operation in place, altering the set on which you call it, and returns None. These four nonmutating methods are also accessible with operator syntax: respectively, S-S1, S&S1, S^S1, and S|S1; the corresponding mutating methods are also accessible with augmented assignment syntax: respectively, Dictionary Operations Python provides a variety of operations applicable to dictionaries. Since dictionaries are containers, the built-in len function can take a dictionary as its single argument and return the number of items (key/value pairs) in the dictionary object. A dictionary is iterable, so you can pass it to any function or method that takes an iterable argument. In this case, only the keys of the dictionary are iterated upon, in some arbitrary order. For example, for any dictionary D , min(D) returns the smallest key in D . Dictionary Membership The k in D operator checks whether object k is one of the keys of the dictionary D . It returns True if it is and False if it isn't. k not in D is just like
blog comments powered by Disqus |