Using Sets in Python
Python has a set data structure built-in.
Declaring a set
Sets do not have duplicates, not can they contain mutable items such as lists, but a set can be formed from a list:
Adding elements to a set
Empty sets are created using the set()
function on a dictionary with no arguments and elements are added to the set object using the methods add()
for a single element and update()
for multiple:
Removing elements from a set
Elements can be removed using either remove()
which raises an error if the element can not be found, or discard()
, or to clear all elements use clear()
.
Python permits set operations as well.
Set Operations: Union
Use the "|" operator, or call the union
method on a set object:
Set Operations: Intersection
Use the "&" operator, or call the intersection
method:
Take it further
There are a lot of other built in methods and functions for processing sets and you are encouraged to explore further, see for example the following: