Section 7.9. Set Type Built-in Methods


7.9. Set Type Built-in Methods

7.9.1. Methods (All Set Types)

We have seen the operator equivalents to most of the built-in methods, summarized in Table 7.4.

Table 7.4. Set Type Methods

Method Name

Operation

s.issubset(t)

Returns TRue if every member of s is in t, False otherwise

s.issuperset(t)

Returns true if every member of s is in t, False otherwise

s.union(t)

Returns a new set with the members of s or t

s.intersection(t)

Returns a new set with members of s and t

s.difference(t)

Returns a new set with members of s but not t

s.symmetric_difference(t)

Returns a new set with members of s or t but not both

s.copy()

Returns a new set that is a (shallow) copy of s


The one method without an operator equivalent is copy(). Like the dictionary method of the same name, it is faster to create a copy of the object using copy() than it is using a factory function like set(), frozenset(), or dict().

7.9.2. Methods (Mutable Sets Only)

Table 7.5 summarizes all of the built-in methods that only apply to mutable sets, and similar to the methods above, we have already seen most of their operator equivalents.

Table 7.5. Mutable Set Type Methods

Method Name

Operation

s.update(t)

Updates s with elements added from t; in other words, s now has members of either s or t

s.intersection_update(t)

Updates s with members of both s and t

s.difference_update(t)

Updates s with members of s without elements of t

s.symmetric_difference_update(t)

Updates s with members of s or t but not both

s.add(obj)

Adds object obj to set s

s.remove(obj)

Removes object obj from set s; KeyError raised if obj is not an element of s (obj not in s)

s.discard(obj)

Removes object obj if obj is an element of s (obj in s)

s.pop()

Removes and returns an arbitrary object of s

s.clear()

Removes all elements from s


The new methods here are add(), remove(), discard(), pop(), and clear(). For the methods that take an object, the argument must be hashable.

7.9.3. Using Operators versus Built-in Methods

As you can see, there are many built-in methods that have near-equivalents when using operators. By "near-equivalent," we mean that there is one major difference: when using the operators, both operands must be sets while for the methods, objects can be iterables too. Why was it implemented this way? The official Python documentation states that "[this] precludes error-prone constructions like set('abc') [and] 'cbs' in favor of the more readable set('abc').intersection('cbs')."



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net