Python provides two set types: set and frozenset. Both are unordered, so neither is a sequence. Sets are mutable, so items can be added and removed. Frozensets are immutable and cannot be changed; however, this means that they are suitable for use as dictionary keys.

Every item in a set is unique; if we try to add an item that is already in a set the add() call does nothing. Two sets are equal if they contain the same items, no matter what order those items were inserted in. Sets are similar to dictionaries that have only keys and no values. Lists, on the other hand keep, their items in insertion order (unless they are sorted), and allow duplicates.

A frozenset is constructed with a single sequence parameter—for example a tuple or a list. A set can be constructed in the same way. For example:

>>> unicorns = set(("Narwhal", "Oryx", "Eland"))

>>> "Mutant Goat" in unicorns


Since we created a set rather than a frozenset we can add and remove items. For example:

>>> unicorns.add("Mutant Goat") >>> unicorns set(['Oryx', 'Mutant Goat', 'Eland', 'Narwhal']) >>> unicorns.add("Eland") >>> unicorns set(['Oryx', 'Mutant Goat', 'Eland', 'Narwhal']) >>> unicorns.remove("Narwhal") >>> unicorns set(['Oryx', 'Mutant Goat', 'Eland'])

The set classes also support the standard set operations—for example, union, intersection, and difference—and for some operations provide both methods and operators, as Table 1.6 shows.

Was this article helpful?

0 0
Video Traffic Guru

Video Traffic Guru

You Can Drive THOUSANDS of Hungry Buyers to Your Offer. Over the last few months I've seen hundreds of video marketers struggle to make good money. Even though they put out video after video, they just aren't getting the kind of passive income they'd always wanted.

Get My Free Ebook

Post a comment