Python Sets

Comprehensive Guide to Python Sets

1. Creating a Set

A set can be created by enclosing comma-separated items with curly braces {}.

Python Code - Creating a Set
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}  

print(Days)  
print(type(Days))
Output
{'Wednesday', 'Tuesday', 'Sunday', 'Friday', 'Thursday', 'Saturday', 'Monday'} <class 'set'>

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.

Python Code - Looping Through a Set
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}  

print("Looping through the set elements ... ")  
for i in Days:  
    print(i)
Output
Looping through the set elements... Wednesday Tuesday Friday Thursday Monday

🧠 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.

Python Code - Union
Days1 = {"Mon", "Tue", "Wed", "Sat"}
Days2 = {"Thr", "Fri", "Sat", "Sun", "Mon"}

print(Days1 | Days2)
Output
{'Thr', 'Fri', 'Sun', 'Tue', 'Wed', 'Mon', 'Sat'}

Intersection (&) Operator

The intersection of the two sets gives the elements that are common in both sets.

Python Code - Intersection
Days1 = {"Mon", "Tue", "Wed", "Sat"}
Days2 = {"Thr", "Fri", "Sat", "Sun", "Mon"}

print(Days1 & Days2)
Output
{'Mon', 'Sat'}

Difference (-) Operator

The resulting set is obtained by removing all the elements from Set 1 that are also present in Set 2.

Python Code - Difference
Days1 = {"Mon", "Tue", "Wed", "Sat"}
Days2 = {"Thr", "Fri", "Sat", "Sun", "Mon"}

print(Days1 - Days2)
Output
{'Tue', 'Wed'}

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.

Python Code - len()
num = {1, 2, 3, 4, 5, 6}

print("Length of set :", len(num))
Output
Length of set : 6

max()

Used to find the maximum value in the set.

Python Code - max() with Numbers
num = {1, 2, 3, 4, 5, 6}

print("Max of num set :", max(num))
Output
Max of num set : 6
Python Code - max() with Strings
lang = {'java', 'c', 'python', 'cpp'}

print("Max of lang set :", max(lang))
Output
Max of lang set : python

min()

Used to find the minimum value in the set.

Python Code - min() with Numbers
num = {1, 2, 3, 4, 5, 6}

print("Min of num set :", min(num))
Output
Min of num set : 1
Python Code - min() with Strings
lang = {'java', 'c', 'python', 'cpp'}

print("Min of lang set :", min(lang))
Output
Min of lang set : c

sum()

Returns the sum of all values in the set. Values must be a number type.

Python Code - sum()
num = {1, 2, 3, 4, 5, 6}

print("Sum of set items :", sum(num))
Output
Sum of set items: 21

sorted()

Used to sort all items of a set. Returns a sorted list.

Python Code - sorted() with Numbers
num = {1, 3, 2, 4, 6, 5}

print(sorted(num))
Output
[1, 2, 3, 4, 5, 6]
Python Code - sorted() with Strings
lang = {'java', 'c', 'python', 'cpp'}

print(sorted(lang))
Output
['c', 'cpp', 'java', 'python']
Python Code - sorted() Reverse Order
num = {1, 3, 2, 4, 6, 5}

print(sorted(num, reverse=True))
Output
[6, 5, 4, 3, 2, 1]

set()

Converts a given sequence (string, list, tuple) into a set.

Python Code - String to Set
set1 = set("PYTHON")

print(set1)
Output
{'N', 'O', 'T', 'H', 'P', 'Y'}
Python Code - List to Set
days_list = ["Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"]
set2 = set(days_list)

print(set2) 
Output
{'Fri', 'Thur', 'Tue', 'Sun', 'Mon', 'Sat', 'Wed'}
Python Code - Tuple to Set
days_tuple = ("Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun")
set3 = set(days_tuple)

print(set3)
Output
{'Fri', 'Thur', 'Tue', 'Sun', 'Mon', 'Sat', 'Wed'}

4. Adding & Removing Elements

add()

Adds a particular item to the set.

Python Code - add()
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)
Output
Printing the original set... {'Wednesday', 'Friday', 'Thursday', 'Tuesday', 'Monday'} Printing the modified set... {'Wednesday', 'Sunday', 'Friday', 'Thursday', 'Tuesday', 'Saturday', 'Monday'}

update()

Adds more than one item to the set (via a list or tuple).

Python Code - update()
Months = {"Jan", "Feb", "Mar", "Apr"}
print("Printing the original set...")  
print(Months)

Months.update(["May", "Jun", "Jul"])
print("\nPrinting the modified set...")
print(Months)
Output
Printing the original set... {'Mar', 'Apr', 'Jan', 'Feb'} Printing the modified set... {'Mar', 'Apr', 'Jan', 'Jun', 'May', 'Jul', 'Feb'}

discard()

Removes an item. If the item doesn't exist, Python will not throw an error.

Python Code - discard() Existing Item
Months = {"Jan", "Feb", "Mar", "Apr"}
print("Printing the original set...")  
print(Months)

Months.discard("Apr")
print("\nPrinting the modified set...")
print(Months)
Output
Printing the original set... {'Jan', 'Apr', 'Mar', 'Feb'} Printing the modified set... {'Jan', 'Mar', 'Feb'}
Python Code - discard() Non-Existing Item
Months = {"Jan", "Feb", "Mar"}

Months.discard("May") # Doesn't give an error

print("\nPrinting the modified set...")
print(Months)
Output
Printing the modified set... {'Jan', 'Mar', 'Feb'}

remove()

Removes an item. If the item doesn't exist, Python will throw an error.

Python Code - remove() Existing Item
Months = {"Jan", "Feb", "Mar", "Apr"}
print("Printing the original set...")  
print(Months)

Months.remove("Apr")
print("\nPrinting the modified set...")
print(Months)
Output
Printing the original set... {'Feb', 'Jan', 'Apr', 'Mar'} Printing the modified set... {'Feb', 'Jan', 'Mar'}
Python Code - remove() Non-Existing Item
Months = {"Jan", "Feb", "Mar"}

Months.remove("May") # This gives an error!
Output
KeyError: 'May'

pop()

Removes the last item. (Note: Since sets are unordered, it removes a random item).

Python Code - pop()
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}  
print("Printing the original set...")  
print(Days)

Days.pop()
print("\nPrinting the modified set...")
print(Days)
Output
Printing the original set... {'Monday', 'Wednesday', 'Friday', 'Tuesday', 'Thursday'} Printing the modified set... {'Wednesday', 'Friday', 'Tuesday', 'Thursday'}

clear()

Removes all items from the set.

Python Code - clear()
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}  
print("Printing the original set...")  
print(Days)

Days.clear()
print("\nPrinting the modified set...")
print(Days)
Output
Printing the original set... {'Monday', 'Wednesday', 'Friday', 'Tuesday', 'Thursday'} Printing the modified set... set()

5. Built-in Math Methods

Instead of using operators (like | or &), you can use explicit method names.

union()

Python Code - union()
Days1 = {"Mon", "Tue", "Wed", "Sat"}
Days2 = {"Thr", "Fri", "Sat", "Sun", "Mon"}

print(Days1.union(Days2))
Output
{'Thr', 'Fri', 'Sun', 'Tue', 'Wed', 'Mon', 'Sat'}

intersection()

Python Code - intersection()
Days1 = {"Mon", "Tue", "Wed", "Sat"}
Days2 = {"Thr", "Fri", "Sat", "Sun", "Mon"}

print(Days1.intersection(Days2))
Output
{'Mon', 'Sat'}

difference()

Python Code - difference()
Days1 = {"Mon", "Tue", "Wed", "Sat"}
Days2 = {"Thr", "Fri", "Sat", "Sun", "Mon"}

print(Days1.difference(Days2))
Output
{'Tue', 'Wed'}

issubset()

Returns True if all elements of a set are present in another set.

Python Code - issubset() True
set1 = {1, 2, 3, 4}
set2 = {1, 2, 3, 4, 5, 6, 7, 8, 9}

print(set1.issubset(set2))
Output
True
Python Code - issubset() False
set1 = {1, 2, 3, 4}
set2 = {1, 2, 3, 4, 5, 6, 7, 8, 9}

print(set2.issubset(set1))
Output
False

issuperset()

Returns True if a set has every element of another set.

Python Code - issuperset() False
set1 = {1, 2, 3, 4}
set2 = {1, 2, 3, 4, 5, 6, 7, 8, 9}

print(set1.issuperset(set2))
Output
False
Python Code - issuperset() True
set1 = {1, 2, 3, 4}
set2 = {1, 2, 3, 4, 5, 6, 7, 8, 9}

print(set2.issuperset(set1))
Output
True

🧠 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.

Post a Comment

0 Comments