Sets
Understanding Sets
A set in Python is an unordered collection of unique elements. It's similar to a mathematical set. Sets are defined by enclosing elements within curly braces {}.
Creating a Set
Python
my_set = {1, 2, 3, "apple", True}
Note that sets do not allow duplicate elements. Any duplicates will be automatically removed.
Accessing Set Elements
Unlike lists and tuples, sets are unordered, so you cannot access elements by index. However, you can iterate through the elements using a for loop.
Modifying Sets
Sets are mutable, meaning you can add or remove elements after creation.
Python
my_set = {1, 2, 3}
my_set.add(4) # Add an element
my_set.remove(2) # Remove an element
Set Operations
Sets support various mathematical set operations:
- union: Combines elements from two sets.
- intersection: Returns elements present in both sets.
- difference: Returns elements present in the first set but not in the second.
- symmetric_difference: Returns elements present in either set, but not both.
Python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
union_set = set1 | set2 # or set1.union(set2)
intersection_set = set1 & set2 # or set1.intersection(set2)
difference_set = set1 - set2 # or set1.difference(set2)
symmetric_difference_set = set1 ^ set2 # or set1.symmetric_difference(set2)
Set Methods
Sets have several useful methods:
- add(x): Adds element x to the set.
- remove(x): Removes element x from the set. Raises a KeyError if x is not present.
- discard(x): Removes element x from the set if it is present.
- pop(): Removes and returns an arbitrary element from the set.
- clear(): Removes all elements from the set.
- copy(): Returns a shallow copy of the set.
Use Cases for Sets
- Removing duplicates from a list.
- Membership testing (checking if an element is present in a set).
- Performing set operations like union, intersection, difference.
- Implementing algorithms related to graphs and data structures.
In summary, sets are useful for storing unique elements and performing set operations. They are often used when order doesn't matter and you need to efficiently check for membership or eliminate duplicates.