This is an archived version of the course. Please see the latest version of the course.

Sets

Python also offers a set data structure built in.

A set does not have duplicate elements, nor should the ordering be important.

A set is presented with curly braces {} in Python.

>>> vowels = {"a", "e", "i", "o", "u"}
>>> print(vowels)         # note the ordering
>>> vowels = {"i", "o", "a", "a", "e", "u", "e", "i", "a"}
>>> print(vowels)         

You can also convert another sequence (e.g. list or tuple) into a set using the set() constructor. Here is one practical application for this:

>>> words = ["let", "it", "go", ",", "let", "it", "go", ",", "can't", 
...          "hold", "it", "back", "any", "more", "!"]
>>> vocabulary = set(words)
>>> print(vocabulary)

To create an empty set, you should use the set() constructor. You cannot use {} because you will end up with a dict which also happens to use {} (we will discuss dicts after this).

>>> empty_set = set()
>>> print(empty_set)
>>> print(type(empty_set))
>>> empty_dict = {}
>>> print(type(empty_dict))

You cannot access an element in a set. Why? Hint: Think about the definition of set.

>>> x = {1, 2, 3}
>>> print(x[1])           # NO!

You will need to convert a set to a list if you need to access individual elements.

>>> x = {1, 2, 3}
>>> y = list(x)
>>> print(y[1])

Adding elements to a set

You can use set’s add() method to add a new element to the set.

>>> x = {1, 3, 2}
>>> x.add(4)
>>> print(x)

You can also add multiple elements in one go with the update() method.

>>> x = {8, 2, 5}
>>> x.update([3, 5, 2, 3])
>>> print(x) 

Removing elements from a set

You can remove an element from a set with the discard() method. Python will not do anything if you try to remove an element that is not in the set.

>>> x = {3, 9, 7}
>>> x.discard(3)
>>> print(x)
>>> x.discard(8)
>>> print(x)

A stricter method called remove() will cause Python to raise an error if you try to remove an element that is not in the set. May be useful if you need such a behaviour!

>>> x = {3, 9, 7}
>>> x.remove(8)     # What is the error message?

Set operations

Python provides overloaded operators for various set operations. Some of these are also available as methods of the set object. I will let you explore these on your own.

Operation Math Notation Python Operator Object Methods
Union \(A \cup B\) a_set | b_set a_set.union(b_set)
Intersection \(A \cap B\) a_set & b_set a_set.intersection(b_set)
Difference \(A \setminus B\) a_set - b_set a_set.difference(b_set)
Symmetric difference \(A \triangle B\) a_set ^ b_set a_set.symmetric_difference(b_set)
Membership \(x \in B\) x in b_set  
Non-membership \(x \notin B\) x not in b_set  
Proper Subset \(A \subset B\) a_set < b_set  
Subset \(A \subseteq B\) a_set <= b_set a_set.issubset(b_set)
Proper Superset \(A \supset B\) a_set > b_set  
Superset \(A \supseteq B\) a_set >= b_set a_set.issuperset(b_set)