17.9 Sets: Adding/Removing Elements

Adding and Removing Elements from a Set

To add an element to a set, simply use the add() method:
a_set = set() a_set.add(5) print(a_set) # prints {5}
To add multiple elements, use update():
a_set = set() a_set.update([1, 2, 3]) # any iterable will work print(a_set) # prints {1, 2, 3}
To remove an element, use the discard(), remove(), or pop() method:
a_set = set(['x', 'y', 'z']) a_set.discard('y') print(a_set) # prints {'z', 'x'} a_set.remove('x') print(a_set) # prints {'z'} print(a_set.pop()) # prints 'z'
View on GitHub
The difference between discard and remove is that remove() raises a KeyError when the user tries to remove an object that isn't in the set, while discard() does not raise a KeyError in this situation.
The difference between discard (or remove) and pop is that pop removes and RETURNS a random value from the set.


Ice Cream Shop

An ice cream shop keeps all its available flavors in a set. Every month, it gets a list of all the flavors that are no longer available. Return a new set containing the available flavors this month after all the no-longer-available flavors are removed. It is possible to solve this problem using either discard or remove.
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.