A set in Python is an unordered collection of unique elements. Sets are mutable, meaning you can add or remove elements after the set has been created. They are commonly used to perform mathematical set operations like union, intersection, and difference.
Key Characteristics of Sets:
- Unordered: The elements in a set do not have a specific order, and you cannot access them by index.
- Unique Elements: A set cannot contain duplicate elements. If you try to add a duplicate, it will be ignored.
- Mutable: You can add or remove elements from a set.
Creating a Set
You can create a set using curly braces {} or the set() constructor:
# Using curly braces
my_set = {1, 2, 3, 4}
# Using the set() constructor
another_set = set([1, 2, 3, 4])
Adding and Removing Elements
You can add elements using the add() method and remove elements using the remove() or discard() methods:
# Adding an element
my_set.add(5) # my_set is now {1, 2, 3, 4, 5}
# Removing an element
my_set.remove(3) # my_set is now {1, 2, 4, 5}
# Using discard (does not raise an error if the element is not found)
my_set.discard(10) # No error, my_set remains {1, 2, 4, 5}
Set Operations
Sets support various operations, such as:
-
Union: Combines elements from both sets.
set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1 | set2 # {1, 2, 3, 4, 5} -
Intersection: Gets elements common to both sets.
intersection_set = set1 & set2 # {3} -
Difference: Gets elements in one set but not in the other.
difference_set = set1 - set2 # {1, 2} -
Symmetric Difference: Gets elements in either set but not in both.
symmetric_difference_set = set1 ^ set2 # {1, 2, 4, 5}
Example
Here’s a complete example demonstrating the creation and manipulation of a set:
# Creating a set
my_set = {1, 2, 3, 4}
# Adding an element
my_set.add(5)
# Removing an element
my_set.remove(2)
# Displaying the set
print(my_set) # Output: {1, 3, 4, 5}
Sets are useful for tasks that involve membership testing, removing duplicates from a collection, and performing mathematical operations on collections of data.
