Python Concepts/Sets

Objective

 * Learn about Python sets.
 * Learn how to dynamically manipulate sets.
 * Learn about set math and comparison.
 * Learn about built-in set functions.
 * Learn when to use sets and when not to.

Python Sets
Sets are mutable sequences, like lists. However, sets and lists differ. Unlike lists, you cannot use  nor can you index or slice. Although the set has limitations, it has two advantages. The set can only contain unique items, so if there are two or more items the same, all but one will be removed. This can help get rid of duplicates. A set is an unordered collection with no duplicate elements. (The technical definition: A set object is an unordered collection of distinct hashable objects. ) Secondly, sets can perform set mathematics. This makes Python sets much like mathematical sets. To create a set, use curly braces. To create an empty set you have to use

Set comprehensions
Similarly to list comprehensions, set comprehensions are also supported:

Return  if set   has no elements in common with   set. Sets are disjoint if and only if their intersection is the empty set.

Test whether every element in set  is in   Equivalent to

Symmetric difference
Return a new set with elements in either  or   but not both.

Union
--

Return a new set with elements from  and all

Intersection
--

Return a new set with elements common to  and all

Difference
--

Return a new set with elements in  that are not in

Assignments
String  contains the names of all 50 states of the United States of America with some duplicates and extraneous white space. Use sets, including set comprehensions, to determine the one letter that does not appear in the name of any state.

Why are the letters "N C" sufficient for "North Carolina"?

One Possible Solution

Further Reading or Review

 * Previous Lesson: Tuples
 * This Lesson:Sets
 * Next Lesson: Dictionaries
 * Course Home Page