15. Set#

A set is an abstract data structure that stores unordered collections of unique elements. The primary operations associated with sets include adding elements, removing elements, and checking for membership. A set satifies these key properties.

  • Uniqueness: A set automatically handles duplicate values. If you attempt to add a duplicate element, the set remains unchanged.

  • Unordered: Sets do not maintain the order of elements. The order in which elements are added does not affect their storage or retrieval.

Sets are implemented with hashtable as its underlying data structure. This explains the fast access to element of a set. In first version of Python interpreter, sets were implemented using dictionary. Nowadays, set and dict’s implementations have diverged significantly.

15.1. Common Operations#

Add an Element: Adds a new element to the set if it is not already present.

my_set.add(element)

Remove an Element: Removes an element from the set. If the element is not found, it can raise an exception (e.g., KeyError in Python).

my_set.remove(element)

Check Membership: Tests whether an element is in the set.

element in my_set

Union: Combines all elements from two sets, yielding a new set containing all unique elements from both.

set1.union(set2)

Intersection: Finds all elements that are common to both sets.

set1.intersection(set2)

Difference: Computes elements that are in the first set but not in the second set.

set1.difference(set2)

Symmetric Difference: Computes elements that are in either of the sets but not in both.

set1.symmetric_difference(set2)