A Python Set
An unordered collection of unique elements. It automatically removes duplicates.
How to create an empty set in Python
Use set() - not {} which creates a dictionary.
Method to add a single element to a set
.add(element)
Method to remove an element, which raises an error if the element isn’t there
.remove(element)
Method to remove an element, which does nothing if the element isn’t there (safer)
.discard(element)
Operation to find all elements in either of two sets (A or B)
Union (set1 | set2 or set1.union(set2))
Operation to find elements common to both of two sets (A and B)
Intersection (set1 & set2 or set1.intersection(set2))
Operation to find elements in the first set but not in the second (A minus B)
Difference (set1 - set2 or set1.difference(set2))
Operation to find elements in either set, but not in both (A XOR B)
Symmetric Difference (set1 ^ set2 or set1.symmetric_difference(set2))
What is the main advantage of using a set over a list for checking if an item exists?
Speed (membership testing is very fast, O(1), in sets)