Introduction
Welcome to this lab on Python Sets! Python provides several built-in data types to organize data, including lists, dictionaries, tuples, and sets.
According to the official Python documentation, a set is an unordered collection with no duplicate elements. Its primary uses are for membership testing and eliminating duplicate entries.
In this lab, you will explore how to create, manipulate, and use sets effectively through a series of hands-on exercises.
Initializing a Set
In this step, you will learn the two primary ways to create sets in Python: using curly braces {} and the built-in set() function. It's crucial to understand that using empty curly braces {} creates an empty dictionary, not an empty set.
Note: If you are not familiar with using WebIDE (VS Code like), please learn it first at this lab.
First, open the step1.py file from the file explorer on the left.
Now, copy and paste the following code into step1.py. This code demonstrates how to create sets and highlights the special case of creating an empty set.
## Create set using curly braces or set() function
s_braces = {1, 2, 3}
print(f"Set with braces: {s_braces}, type: {type(s_braces)}")
s_func = set([1, 2, 3])
print(f"Set with function: {s_func}, type: {type(s_func)}")
## Warning: empty {} creates a dictionary, not a set
s_dict = {}
print(f"Empty braces create a: {type(s_dict)}")
## To create an empty set, you must use set()
s_empty = set()
print(f"To create an empty set use set(): {type(s_empty)}")
Save the file, and then run it from the terminal by executing the following command:
python3 step1.py
You should see the following output, which confirms the types of the created objects. Notice that {} results in <class 'dict'>.
Set with braces: {1, 2, 3}, type: <class 'set'>
Set with function: {1, 2, 3}, type: <class 'set'>
Empty braces create a: <class 'dict'>
To create an empty set use set(): <class 'set'>
Understanding Set Properties
In this step, you will explore the core properties of sets. Sets are powerful because they automatically enforce uniqueness and are unordered. This means a set will automatically remove any duplicate values, and you cannot access its elements using an index.
Open the step2.py file.
Copy and paste the following code into step2.py. The first part of the code demonstrates how duplicates are handled, and the second part shows what happens when you try to index a set.
## Sets automatically remove duplicates
s_duplicates = {1, 2, 3, 2, 3, 4}
print(f"Original with duplicates: {{1, 2, 3, 2, 3, 4}}")
print(f"Set with duplicates removed: {s_duplicates}")
## Sets are unordered and cannot be indexed
print("\nAttempting to access a set by index...")
try:
s = {1, 2, 3}
s[0]
except TypeError as e:
print(f"Error when indexing: {e}")
Now, run the script from the terminal:
python3 step2.py
The output will be:
Original with duplicates: {1, 2, 3, 2, 3, 4}
Set with duplicates removed: {1, 2, 3, 4}
Attempting to access a set by index...
Error when indexing: 'set' object is not subscriptable
As you can see, the duplicate 2 and 3 were automatically removed. The attempt to access s[0] resulted in a TypeError, confirming that sets do not support indexing.
Adding and Updating Elements
In this step, you will learn how to add new elements to an existing set. Python provides two main methods for this: add() to add a single element and update() to add multiple elements from an iterable (like a list or another set).
Open the step3.py file.
Copy and paste the following code into step3.py. This code will first create a set, then add a single element, and finally update it with multiple elements.
## Start with a set
s = {1, 2, 3}
print(f"Original set: {s}")
## add() method: add a single element
s.add(4)
print(f"After adding 4: {s}")
## update() method: add multiple elements from an iterable
s.update([2, 3, 4, 5, 6]) ## Duplicates like 2, 3, 4 are ignored
print(f"After updating with [2, 3, 4, 5, 6]: {s}")
Execute the script from the terminal:
python3 step3.py
Your output should look like this. Note that when using update(), any elements that are already in the set are simply ignored.
Original set: {1, 2, 3}
After adding 4: {1, 2, 3, 4}
After updating with [2, 3, 4, 5, 6]: {1, 2, 3, 4, 5, 6}
Removing and Discarding Elements
In this step, you will learn two ways to remove elements from a set: remove() and discard(). While both methods remove an element, they behave differently when the element is not found. remove() will raise a KeyError, which can crash your program if not handled, whereas discard() will do nothing and continue silently.
Open the step4.py file.
Copy and paste the following code, which demonstrates the behavior of both methods.
## remove() method: raises KeyError if element is not found
s = {1, 2, 3}
print(f"Original set: {s}")
s.remove(3)
print(f"After removing 3: {s}")
## Trying to remove an element that doesn't exist with remove()
try:
s.remove(3)
except KeyError as e:
print(f"Error when removing 3 again: KeyError: {e}")
## discard() method: does not raise an error if element is not found
s = {1, 2, 3}
print(f"\nNew original set: {s}")
s.discard(3)
print(f"After discarding 3: {s}")
s.discard(3) ## No error is raised
print(f"After discarding 3 again (no error): {s}")
Run the script from the terminal:
python3 step4.py
The output clearly shows the difference:
Original set: {1, 2, 3}
After removing 3: {1, 2}
Error when removing 3 again: KeyError: 3
New original set: {1, 2, 3}
After discarding 3: {1, 2}
After discarding 3 again (no error): {1, 2}
Choosing between remove() and discard() depends on whether you want your program to fail explicitly when an element is missing or to handle its absence gracefully.
Set Operations
In this final step, you will practice the most common set operations. These operations allow you to combine and compare sets in powerful ways. You will use both the method syntax (e.g., s1.union(s2)) and the operator syntax (e.g., s1 | s2).
- Union (
union()or|): Creates a new set with all elements from the sets provided. - Intersection (
intersection()or&): Returns a new set with only the elements that are common to all sets. - Difference (
difference()or-): Returns a new set with elements that are in the first set but not in the second. - Symmetric Difference (
symmetric_difference()or^): Returns a new set with elements that are in either set, but not in both.
Open the step5.py file.
Copy and paste the following code to perform these four operations on two sample sets.
s1 = {1, 2, 3}
s2 = {2, 3, 4}
print(f"s1 = {s1}")
print(f"s2 = {s2}\n")
## union() or |
## Returns a new set containing all items from both sets.
print(f"Union (s1 | s2): {s1.union(s2)}")
## intersection() or &
## Returns a new set containing items common to both sets.
s3 = {3, 4, 5}
print(f"Intersection (s1 & s2): {s1.intersection(s2)}")
## difference() or -
## Returns a new set containing items in the first set but not in the second.
print(f"Difference (s1 - s2): {s1.difference(s2)}")
print(f"Difference (s2 - s1): {s2.difference(s1)}")
## symmetric_difference() or ^
## Returns a new set with elements in either set, but not both.
print(f"Symmetric Difference (s1 ^ s2): {s1.symmetric_difference(s2)}")
Run the script from the terminal:
python3 step5.py
Examine the output to understand the result of each operation:
s1 = {1, 2, 3}
s2 = {2, 3, 4}
Union (s1 | s2): {1, 2, 3, 4}
Intersection (s1 & s2): {2, 3}
Difference (s1 - s2): {1}
Difference (s2 - s1): {4}
Symmetric Difference (s1 ^ s2): {1, 4}
Summary
In this lab, you have learned the fundamentals of Python sets. You started by initializing sets using both curly braces {} and the set() function, noting the important distinction for creating empty sets. You explored the core properties of sets: they are unordered and only store unique elements. You practiced modifying sets by adding elements with add() and update(), and removing them with the remove() and discard() methods, understanding the key difference between them. Finally, you performed essential set operations including union (|), intersection (&), difference (-), and symmetric difference (^). You now have a solid foundation for using sets to handle collections of unique items in your Python programs.



