This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: Set

Sets

face Josiah Wang

So far, I have introduced you to the following Python data structures:

  • Sequence: list, tuple, range, str
  • Maps: dict

We will now look at another Python data structure called set.

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

A set is presented with curly braces {} in Python (just like a dict - don’t get confused!)

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

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

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

To create an empty set, you should use set().

You cannot use {} because you will end up with a dict!

>>> empty_set = set()
>>> print(empty_set)
set()
>>> print(type(empty_set))
<class 'set'>
>>> empty_dict = {}
>>> print(type(empty_dict))
<class 'dict'>