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

Chapter 2: Set

Set methods

face Josiah Wang

sets are mutable. This means you can modify the values of the set.

The official documentation lists some mutator methods, for example add(), update(), discard(), remove(), pop(), clear(). There are a few others, but I will let you explore the documentation yourself.

Let’s quickly explore the methods with a quiz!

1 2 3 4 5

Question 1

What is the output after executing the following piece of code? Type Error if you are expecting an error.

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

{1, 2, 3, 4}
Explanation:

It is fine if your ordering is different from my answer (my version of Python gave me that ordering), as long as you have all four elements in your set. The .add() method adds a new element to the set (without duplicating any existing elements).

Question 2

What is the output after executing the following piece of code? Type Error if you are expecting an error.

1
2
3
x = {1}
x.update([2, 3, 1, 3, 1, 3])
print(x)

{1, 2, 3}
Explanation:

Again, it is fine if your ordering is different from my answer, as long as you have all three elements in your set. The .update() element can take a sequence or a set as its argument. Alternatively, you can use the augmented assignment operator |=, i.e. x |= {2, 3, 1, 3, 1, 3}.

Question 3

What is the output after executing the following piece of code? Type Error if you are expecting an error.

1
2
3
x = {3, 1}
x.discard(3)
print(x)

{1}
Explanation:

Quite self-explanatory. The .discard() method discards an element from a set.

Question 4

What is the output after executing the following piece of code? Type Error if you are expecting an error.

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

{2}
Explanation:

The .discard() method does not do anything if an element to discard is not found.

Question 5

What is the output after executing the following piece of code? Type Error if you are expecting an error.

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

Error
Explanation:

The .remove() method is a stricter version of .discard(). It raises a KeyError if a given element does not exist in the set. You might want this behaviour, depending on your needs (maybe you want to enforce that you cannot remove something that does not exist?) You can handle the KeyError with a try... except block.