Sets

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

False

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
Tuberminator

Tuberminator

The main focus of this report is to show how to get involved in video marketing on the run, how to rank quickly on YouTube and Google using FREE semi-automatic tools and services. QUICKLY AND FREE. I will show methods and techniques I use to rank my videos, as well as free resources and tools to make video clips, to get backlinks and free traffic.

Get My Free Ebook


Post a comment