Click here to view code image
set_name.update([element(s)_to_add])
In Listing 9.25, a mass addition is made to the students_in_108 set, using the update
operation. As you can see, two additional elements are added to the set in a mass add.
LISTING 9.25 Updating a Set
Click here to view code image
>>> students_in_108
{'Paul Bohall', 'Raz Pi', 'Jason Jones'}
>>> students_in_108.update(['Alan Griffith','Otis McCallum'])
>>> students_in_108
{'Otis McCallum', 'Paul Bohall', 'Raz Pi', 'Jason Jones', 'Alan Griffith'}
>>>
You can also delete elements from a set. There are two set operations available for deleting elements.
The first is the remove operation, which has this syntax:
Click here to view code image
set_name.remove([element(s)_to_remove])
The other is the discard operation, which has this syntax:
Click here to view code image
set_name.discard([element(s)_to_discard])
Listing 9.26 uses the remove operation to remove two students from the students_in_108 set.
LISTING 9.26 Deleting Elements from a Set
Click here to view code image
>>> students_in_108
{'Otis McCallum', 'Paul Bohall', 'Raz Pi', 'Jason Jones', 'Alan Griffith'}
>>> students_in_108.remove('Alan Griffith')
>>> students_in_108.remove('Otis McCallum')
>>> students_in_108
{'Paul Bohall', 'Raz Pi', 'Jason Jones'}
>>>
The primary difference between doing a remove operation and a discard operation on a set has
to do with missing elements. As shown in Listing 9.27, if an element does not exist in the set and you
attempt remove it, an error exception is thrown. With a discard operation, no error exception is
given.
LISTING 9.27 The Difference Between remove and discard
Click here to view code image