13_Set in Python
13_Set in Python
Learning objective
• Python Set - Introduction
• Creating a Set
• Can we access element of Set?
• Updating Set
• Delete Set Elements
• Mathematical Set operations
• Union
• Intersection
• Minus
Python Set - Introduction
• Collection of the unordered items. Each element in the set must
be unique, immutable, and the sets remove the duplicate
elements.
• Sets are mutable which means we can modify it after its creation.
• However, we can print them all together, or we can get the list of
elements by looping through the set.
Creating a Set
• The set can be created by enclosing the comma separated
immutable items with the curly braces {}.
• Python also provides the set() method, which can be used to
create the set by the passed sequence.
my_set = {1, 2, 3, 4, 5}
# Checking if an element exists in the set
element_to_check = 3
if element_to_check in my_set:
print(f"{element_to_check} exists in the set.")
else:
print(f"{element_to_check} does not exist in the set.")
Updating Set
• Sets are mutable, meaning you can add and remove elements from
them, but you cannot directly update an individual element by index
because sets are unordered collections.
• If you want to update a set, you typically add or remove elements.
my_set = {1, 2, 3, 4, 5}
# Adding an element to the set
my_set.add(6)
print("After adding 6:", my_set)
# Removing an element from the set
my_set.remove(3)
print("After removing 3:", my_set)
Deleting Set Elements
• Use remove() or discard() method to remove a specific element.
• discard() does not raise an error if the element is not present in the set.
• Also, use the pop() method to remove and return an arbitrary element from the set.
my_set = {1, 2, 3, 4, 5}
my_set.remove(3) # Remove a specific element
print("After removing 3:", my_set)
my_set.discard(5) # Discard a specific element
print("After discarding 5:", my_set)
# Remove and return an arbitrary element
removed_element = my_set.pop()
print("Removed element:", removed_element)
print("Set after pop operation:", my_set)
Mathematical Set operations
• You can perform various mathematical set operations using the built-in
set methods.
• Union: Returns a set containing all unique elements from both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
Mathematical Set operations
• Intersect: Returns a set containing common elements from both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3}
Mathematical Set operations
• Difference: Returns a set containing elements that are in the first set
but not in the second set.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}
You must have learnt:
• Python Set - Introduction
• Creating a Set
• Can we access element of Set?
• Updating Set
• Delete Set Elements
• Mathematical Set operations
• Union
• Intersection
• Minus