Previous Lesson | Table of Contents | Next Lesson |
Lists and tuples are useful for keeping together collections of objects, but they make no guarantees regarding the uniqueness of the elements. Uniqueness can be useful, for example, if you want to count the number of unique customers that have entered your store, given that the same customer can enter and exit your store multiple times on any given day.
A set
is the class for collections of unique elements. Unlike tuple
,
set
is mutable, meaning we can add and remove objects from it. However,
this mutability property has additional significance that we’ll revisit later.
In addition to mutability, set
cannot be indexed. That is, the bracket
indexing syntax seen before will not work with set
.
To create a set
, we use curly braces instead of brackets or parentheses to
surround our comma-delimited collection of Python objects:
s = {1, 2, 3, 2}
print(s)
This will output:
{1, 2, 3}
Note that we deliberately passed in two 2
objects, but Python was able to
deduce that they were exactly same and omit the last one.
To add an element to our set
, we just use the add
method:
s = {1, 2, 3}
s.add("cat")
print(s)
This will output:
{1, 2, 3, 'cat'}
Note that if we had tried to add an object that already existed in the set
,
it would remain unchanged. To remove an element from our set
, we just use the remove
method:
s = {1, 2, 3}
s.remove(1)
print(s)
This will output:
{2, 3}
What happens if we attempt to remove an element that already does not exist?
s = {1, 2, 3}
s.remove(4)
As with list
, Python will raise an error:
...
KeyError: 4
Before concluding, we should revisit the mutable property of list
, tuple
,
set
, and Python objects in general. One requirement of set
is that it can
only contain Python objects that are immutable. Numbers, strings, and
tuple
are immutable. list
and set
are not, unfortunately.
What happens if we try to create a set
with a mutable object?
s = {[1, 2], 3}
Not surprisingly, Python will raise an error:
...
TypeError: unhashable type: 'list'
With that caveat explained, let’s practice what we have learned with sets:
Create a
set
with the following elements:1
,"dog"
,"cat"
, and1
. How many elements are in ourset
? (solution)With your newly-created
set
, add the following elements:3
,"house"
, and"cat"
. Then remove the element1
. How many elements are in ourset
now? (solution)
If you feel comfortable with sets, feel free to move on to Lesson 9!