15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

!= Is not equal to<br />

< Is a (strict) subset of<br />

Is a (strict) superset of<br />

>= Is a superset of (includes improper supersets)<br />

& Intersection<br />

| Union<br />

- or \ - Difference or relative complement<br />

Δ ^ Symmetric difference<br />

How to Create and Assign Set Types<br />

There is no special syntax for sets like there is for lists ( [ ] ) and dictionaries ( { } ) for example. Lists<br />

and dictionaries can also be created with their corresponding factory functions list() and dict(), and<br />

that is also the only way sets can be created, using their factory functions set() and frozenset():<br />

>>> s = set('cheeseshop')<br />

>>> s<br />

set(['c', 'e', 'h', 'o', 'p', 's'])<br />

>>> t = frozenset('bookshop')<br />

>>> t<br />

frozenset(['b', 'h', 'k', 'o', 'p', 's'])<br />

>>> type(s)<br />

<br />

>>> type(t)<br />

<br />

>>> len(s)<br />

6<br />

>>> len(s) == len(t)<br />

True<br />

>>> s == t<br />

False<br />

How to Access Values in Sets<br />

You are either going to iterate through set members or check if an item is a member (or not) of a set:<br />

>>> 'k' in s<br />

False<br />

>>> 'k' in t<br />

True<br />

>>> 'c' not in t<br />

True<br />

>>> for i in s:

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

Saved successfully!

Ooh no, something went wrong!