04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

222 CHAPTER 10 ■ BATTERIES INCLUDED<br />

Just as with dictionaries, the ordering of set elements is quite arbitrary, and shouldn’t be<br />

relied on:<br />

>>> set(['fee', 'fie', 'foe'])<br />

set(['foe', 'fee', 'fie'])<br />

In addition to checking for membership, you can perform various standard set operations<br />

(which you may know from mathematics) such as union and intersection, either by using methods<br />

or by using the same operations as you would for bit operations on integers (see Appendix B).<br />

For example, you can find the union of two sets using either the union method of one of them<br />

or the bitwise OR operator, |:<br />

>>> a = set([1, 2, 3])<br />

>>> b = set([2, 3, 4])<br />

>>> a.union(b)<br />

set([1, 2, 3, 4])<br />

>>> a | b<br />

set([1, 2, 3, 4])<br />

Here are some other methods and their corresponding operators; the names should make<br />

it clear what they mean:<br />

>>> c = a & b<br />

>>> c.issubset(a)<br />

True<br />

>>> c >> c.issuperset(a)<br />

False<br />

>>> c >= a<br />

False<br />

>>> a.intersection(b)<br />

set([2, 3])<br />

>>> a & b<br />

set([2, 3])<br />

>>> a.difference(b)<br />

set([1])<br />

>>> a - b<br />

set([1])<br />

>>> a.symmetric_difference(b)<br />

set([1, 4])<br />

>>> a ^ b<br />

set([1, 4])<br />

>>> a.copy()<br />

set([1, 2, 3])<br />

>>> a.copy() is a<br />

False

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!