Tutorial 9.1 - Advanced Data Structures
Sets and their operations
In Python, a set is an unordered collection of unique Elements. Sets are used for various purposes, including removing duplicates from a list, membership testing, and performing mathematical set operations. Here's an overview of sets and their operations in Python:1. Creating Sets:
You can create a set by enclosing a sequence of elements within curly braces `{}` or by using the `set()` constructor.fruits = {"apple", "banana", "cherry"}
empty_set = set()
fruits.add("grape")
2. Adding and Removing Elements:
You can add elements to a set using the `add()` method and Remove elements using the `remove()` or `discard()` methods.fruits.add("grape")
fruits.remove("banana")
The `remove()` method raises a `KeyError` if the element is not found, while `discard()` does not.
The `remove()` method raises a `KeyError` if the element is not found, while `discard()` does not.
3. Set Operations:
Sets support various mathematical set operations:- Union: Combines two sets to create a new set containing all unique elements.
- Intersection: Finds common elements between two sets.
- Difference: Finds elements in one set but not in the other.
- Symmetric Difference: Finds elements that are in either of the sets, but not in both.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) # {1, 2, 3, 4, 5}
intersection_set = set1.intersection(set2) # {3}
difference_set = set1.difference(set2) # {1, 2}
symmetric_difference_set = set1.symmetric_difference(set2) # {1, 2, 4, 5}
You can also use operators `|` for union, `&` for intersection, `-` for difference, and `^` for symmetric difference.
union_set = set1 | set2
intersection_set = set1 & set2
difference_set = set1 - set2
symmetric_difference_set = set1 ^ set2
4. Set Methods:
Sets have a variety of methods for performing operations and testing membership:add(): Adds an element to the set.- `remove()`: Removes an element (raises an error if not found).
- `discard()`: Removes an element (no error if not found).
- `pop()`: Removes and returns an arbitrary element.
- `clear()`: Removes all elements from the set.
- `len()`: Returns the number of elements in the set.
- `in` operator: Tests membership.
- `copy()`: Creates a shallow copy of the set.
5. Iterating Through Sets:
You can iterate through a set using a `for` loop:for fruit in fruits:
print(fruit)
fs = frozenset([1, 2, 3])
6. Frozensets:
A frozenset is an immutable version of a set. It can be used as a key in dictionaries because it is hashable.fs = frozenset([1, 2, 3])
Sets are useful for various purposes in Python, such as handling unique values, performing set operations, and solving problems that involve mathematical sets. They are a fundamental data structure in Python and can simplify many programming tasks.