Sets
Sets are data structures similar to lists or dictionaries. These are created using the brackets {} or directly the set() function. This data structure shares some functionalities with lists, for example the use of the in clause to know if a particular value is contained within.
set1 = {1,4,6,3}
set2 = set(["One","Two","Three"])
print(3 in set1)
print("One" in set2)
if you run it, you get:
>>>
True
True
Sets differ from the lists in many respects, for example they are not ordered and therefore there are no indexes that refer to them inside. Furthermore they can not contain duplicate values. As far as performance is concerned, the survey if a value is contained within a set is more efficient than that for a list.
To add an element to a set you have to use the add () method (in the lists you can use append ()), to remove it you have to use remove () and the method pop () returns the first one that was inserted by deleting it from the set.
set1 = set()
set1.add(1)
set1.add(4)
set1.add(6)
print(set1)
print(set1.pop())
print(set1)
set1.remove(6)
print(set1)
if you run it, you get
>>>
{1, 4, 6}
1
{4, 6}
{4}
Operators on sets
Sets can be used to perform some mathematical operations typical of sets.
- Union – the operator | combines two sets to form a new one
- Intersection – the & operator returns a new set containing the values included in both the initial sets
- Difference – the operator – returns the values included in the first set that are not present in the second set
- Symmetric difference – the operator ^ returns the values of the two sets that are not present in both
Let’s see an example
A = {1,4,6,3}
B = {4,5,9,2}
print(A | B)
print(A & B)
print(A - B)
print(A ^ B)
if you run it, you get
>>>
{1, 2, 3, 4, 5, 6, 9}
{4}
{1, 3, 6}
{1, 2, 3, 5, 6, 9}