Introduction to Sets#

Introduction#

This notebook was created by Jupyter AI with the following prompt:

/generate A Python notebook that teaches how to use sets

This Jupyter notebook provides a comprehensive guide on how to use sets in Python. It covers various topics such as creating a set, adding and removing elements from a set, checking if an element is in a set, and performing set operations. The notebook’s description emphasizes its purpose to teach users about sets, and the prompt highlights the main topic of the notebook.

Adding Elements to a Set#

[1]:
# Improving the code
my_set = {1, 2, 3}
print(my_set)
{1, 2, 3}

Removing Elements from a Set#

[2]:
my_set = {1, 2, 3, 4, 5}
[3]:
print("Original set:", my_set)
Original set: {1, 2, 3, 4, 5}
[4]:
my_set.remove(3)
print("After removing '3':", my_set)
After removing '3': {1, 2, 4, 5}
[5]:
my_set.discard(5)
print("After discarding '5':", my_set)
After discarding '5': {1, 2, 4}
[6]:
removed_element = my_set.pop()
print("Removed element:", removed_element)
print("After popping an element:", my_set)
Removed element: 1
After popping an element: {2, 4}

Checking if an Element is in a Set#

[7]:
# Checking if an Element is in a Set
[8]:
# Create a set
my_set = {1, 2, 3, 4, 5}
[9]:
# Check if an element is in the set
element = 3
if element in my_set:
    print(f"{element} is in the set.")
else:
    print(f"{element} is not in the set.")
3 is in the set.

Set Operations#

[10]:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
[11]:
union_set = set1 | set2
print("Union of set1 and set2:", union_set)
Union of set1 and set2: {1, 2, 3, 4, 5, 6, 7, 8}
[12]:
intersection_set = set1 & set2
print("Intersection of set1 and set2:", intersection_set)
Intersection of set1 and set2: {4, 5}
[13]:
difference_set = set1 - set2
print("Difference between set1 and set2:", difference_set)
Difference between set1 and set2: {1, 2, 3}
[14]:
symmetric_difference_set = set1 ^ set2
print("Symmetric difference between set1 and set2:", symmetric_difference_set)
Symmetric difference between set1 and set2: {1, 2, 3, 6, 7, 8}