Set is Python
• A set is an unordered collection of unique elements.
• Sets are used to store multiple items in a single variable, but only unique values
are stored.
• Sets are mutable, meaning you can add or remove elements after the set is
created.
Creating a Set
A set is created by placing elements inside curly braces {} or by using the set()
constructor.
1. Set1 = {1, 2, 3, 4}
2. empty_set = set() # To create an empty set, since {} creates an empty dictionary
3. Creating a set from a list (to remove duplicates)
list_with_duplicates = [1, 2, 2, 3, 4]
set2 = set(list_with_duplicates) #will remove duplicates
Adding Elements to a Set: Use the add() method to add a single element to the set.
Set1 = {1, 2, 3}
[Link](4)
print(Set1) # Output: {1, 2, 3, 4}
Removing Elements from a Set
• Use the remove() or discard() methods to remove an element from a set.
• remove() raises an error if the element is not found, while discard() does not.
Set1 = {1, 2, 3, 4}
[Link](2) # Removes element 2
[Link](5) # Does nothing, since 5 is not in the set (no error raised)
# error- [Link](6)
print(Set1)
Common Set Operations
• Union (|): Combines two sets and returns a new set with all unique elements
from both sets.
• Intersection (&): Returns a new set with elements common to both sets.
• DiFerence (-): Returns a new set with elements that are in the first set but not in
the second.
• Symmetric DiFerence (^): Returns a new set with elements that are in either of
the sets, but not in both.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union
print(set1 | set2) # Output: {1, 2, 3, 4, 5}
# Intersection
print(set1 & set2) # Output: {3}
# DiWerence
print(set1 - set2) # Output: {1, 2}
# Symmetric DiWerence
print(set1 ^ set2) # Output: {1, 2, 4, 5}
Membership Testing
Set1 = {1, 2, 3}
print(2 in Set1) # True
print(4 in Set1) # False
Iterating Through a Set
my_set = {1, 2, 3}
for item in my_set:
print(item)