1. Creating a Set
A set can be created by enclosing comma-separated items with curly braces {}.
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
Note: Because sets are unordered, the order of elements in the output may vary each time you run the code!
Because there is no index, we can get the list of elements by looping through the set.
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
print("Looping through the set elements ... ")
for i in Days:
print(i)
🧠Pop Quiz 1: Set Rules
Question: What happens if you try to create a set with duplicate values, like {1, 2, 2, 3}?
Click here to reveal the answer
Answer: The set will automatically remove the duplicates. The resulting set will just be {1, 2, 3}.
2. Mathematical Set Operators
In Python, we can perform standard mathematical operations on sets using specialized operators.
| Operator | Description |
|---|---|
| |
Union Operator: Combines items from both sets (no duplicates). |
& |
Intersection Operator: Returns only items common to both sets. |
- |
Difference Operator: Removes items of set 2 from set 1. |
Union (|) Operator
The union of the two sets contains all the items that are present in both the sets.
Days1 = {"Mon", "Tue", "Wed", "Sat"}
Days2 = {"Thr", "Fri", "Sat", "Sun", "Mon"}
print(Days1 | Days2)
Intersection (&) Operator
The intersection of the two sets gives the elements that are common in both sets.
Days1 = {"Mon", "Tue", "Wed", "Sat"}
Days2 = {"Thr", "Fri", "Sat", "Sun", "Mon"}
print(Days1 & Days2)
Difference (-) Operator
The resulting set is obtained by removing all the elements from Set 1 that are also present in Set 2.
Days1 = {"Mon", "Tue", "Wed", "Sat"}
Days2 = {"Thr", "Fri", "Sat", "Sun", "Mon"}
print(Days1 - Days2)
3. Set Functions & Methods
Python contains several built-in functions and methods to evaluate and manipulate sets.
len()
Used to find the length of the set.
num = {1, 2, 3, 4, 5, 6}
print("Length of set :", len(num))
max()
Used to find the maximum value in the set.
num = {1, 2, 3, 4, 5, 6}
print("Max of num set :", max(num))
lang = {'java', 'c', 'python', 'cpp'}
print("Max of lang set :", max(lang))
min()
Used to find the minimum value in the set.
num = {1, 2, 3, 4, 5, 6}
print("Min of num set :", min(num))
lang = {'java', 'c', 'python', 'cpp'}
print("Min of lang set :", min(lang))
sum()
Returns the sum of all values in the set. Values must be a number type.
num = {1, 2, 3, 4, 5, 6}
print("Sum of set items :", sum(num))
sorted()
Used to sort all items of a set. Returns a sorted list.
num = {1, 3, 2, 4, 6, 5}
print(sorted(num))
lang = {'java', 'c', 'python', 'cpp'}
print(sorted(lang))
num = {1, 3, 2, 4, 6, 5}
print(sorted(num, reverse=True))
set()
Converts a given sequence (string, list, tuple) into a set.
set1 = set("PYTHON")
print(set1)
days_list = ["Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"]
set2 = set(days_list)
print(set2)
days_tuple = ("Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun")
set3 = set(days_tuple)
print(set3)
4. Adding & Removing Elements
add()
Adds a particular item to the set.
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
print("Printing the original set...")
print(Days)
Days.add("Saturday")
Days.add("Sunday")
print("\nPrinting the modified set...")
print(Days)
update()
Adds more than one item to the set (via a list or tuple).
Months = {"Jan", "Feb", "Mar", "Apr"}
print("Printing the original set...")
print(Months)
Months.update(["May", "Jun", "Jul"])
print("\nPrinting the modified set...")
print(Months)
discard()
Removes an item. If the item doesn't exist, Python will not throw an error.
Months = {"Jan", "Feb", "Mar", "Apr"}
print("Printing the original set...")
print(Months)
Months.discard("Apr")
print("\nPrinting the modified set...")
print(Months)
Months = {"Jan", "Feb", "Mar"}
Months.discard("May") # Doesn't give an error
print("\nPrinting the modified set...")
print(Months)
remove()
Removes an item. If the item doesn't exist, Python will throw an error.
Months = {"Jan", "Feb", "Mar", "Apr"}
print("Printing the original set...")
print(Months)
Months.remove("Apr")
print("\nPrinting the modified set...")
print(Months)
Months = {"Jan", "Feb", "Mar"}
Months.remove("May") # This gives an error!
pop()
Removes the last item. (Note: Since sets are unordered, it removes a random item).
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
print("Printing the original set...")
print(Days)
Days.pop()
print("\nPrinting the modified set...")
print(Days)
clear()
Removes all items from the set.
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
print("Printing the original set...")
print(Days)
Days.clear()
print("\nPrinting the modified set...")
print(Days)
5. Built-in Math Methods
Instead of using operators (like | or &), you can use explicit method names.
union()
Days1 = {"Mon", "Tue", "Wed", "Sat"}
Days2 = {"Thr", "Fri", "Sat", "Sun", "Mon"}
print(Days1.union(Days2))
intersection()
Days1 = {"Mon", "Tue", "Wed", "Sat"}
Days2 = {"Thr", "Fri", "Sat", "Sun", "Mon"}
print(Days1.intersection(Days2))
difference()
Days1 = {"Mon", "Tue", "Wed", "Sat"}
Days2 = {"Thr", "Fri", "Sat", "Sun", "Mon"}
print(Days1.difference(Days2))
issubset()
Returns True if all elements of a set are present in another set.
set1 = {1, 2, 3, 4}
set2 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(set1.issubset(set2))
set1 = {1, 2, 3, 4}
set2 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(set2.issubset(set1))
issuperset()
Returns True if a set has every element of another set.
set1 = {1, 2, 3, 4}
set2 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(set1.issuperset(set2))
set1 = {1, 2, 3, 4}
set2 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(set2.issuperset(set1))
🧠Pop Quiz 2: Removing Items
Question: Why is it sometimes safer to use discard() instead of remove() in a Python script?
Click here to reveal the answer
Answer: Because if you try to delete an item that isn't actually in the set, remove() will crash your program with a KeyError. discard() will simply do nothing and let the program keep running.
0 Comments