What is Sets in Python?
A set in Python is mutable, iterable, and does not have any duplicate elements. It is an unordered collection of elements which means that a set is a collection that stores elements of different Python Data Types. Remember that a set in Python doesn’t index the elements in a particular order. Let us look at some of the properties of sets in Python. Sets in Python are usually used to perform some mathematical functions such as union, intersection, etc.
 In Python sets, elements don’t have a specific order.
 Sets in Python can’t have duplicates. Each item is unique.
 The elements of a set in Python are immutable. They can’t accept changes once added.
 But, don’t get confused with the fact that sets in Python are mutable. Python sets allow addition and deletion operations.
One of the major advantages of using sets in Python is that unlike some other data types like Python Lists, sets contain a highly optimized method for the sole purpose of checking whether a particular element is included in a set or not.
Also, since sets in Python are mutable, we can add and remove elements from a set; however, every element that is added in the set must be unique and immutable, that is, we cannot change elements once they have been added.
 When to use sets in Python?
 How do you create a set?
 Set Operations
 Finding the length of a Set
 Accessing Set elements
 Adding elements to a Set
 Removing Set elements
 Union of Sets
 Intersection of Sets
 Difference of Sets
 What are Frozen Sets?
 How to Create Frozen Sets?
 Accessing Frozen Set elements
When to Use Sets in Python?
Sets in Python are used when
 The order of data does not matter
 You do not need any repetitions in the data elements
 You need to perform mathematical operations such as union, intersection, etc
Now let us move ahead and see how to create sets in Python.
How do you create a set in Python?
Sets in Python can be created in two ways
 enclosing elements within curly braces
 by using the set() function
1) Using curly braces:
Sets in Python are created using curly braces({}).
Example: My_Set={1,’s’,7.8}
print(My_Set)
Output:{‘s’, 1, 7.8}
As you can see, My_Set has been created.
2) Using set() function
Sets in Python can be created using the set() function.
Example:a= set({1,’b’,6.9})
print(a)
Output:{1, ‘b’, 6.9}
You can also create an empty set using the same function.
Example: Empty_Set=set()
print(Empty_Set)
The above output shows an empty set named Empty_Set has been created.
You can add elements to this empty set. I will be covering that in the following topics.
Set Operations
A number of operations can be performed on sets such as adding elements, deleting elements, finding the length of a set, etc. To know what all methods can be used on sets, you can use the dir() function.
b My_Set={1,’s’,7.8}
dir(My_Set)
Output:[‘__and__’,’__class__’,’__contains__’,’__delattr__’,’__dir__’,’__doc__’,’__eq__’,’__format__’,’__ge__’,’__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__iand__’, ‘__init__’, ‘__init_subclass__’, ‘__ior__’, ‘__isub__’, ‘__iter__’, ‘__ixor__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__or__’, ‘__rand__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__ror__’, ‘__rsub__’, ‘__rxor__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__sub__’, ‘__subclasshook__’, ‘__xor__’, ‘add’, ‘clear’, ‘copy’, ‘difference’, ‘difference_update’, ‘discard’, ‘intersection’, ‘intersection_update’, ‘isdisjoint’, ‘issubset’, ‘issuperset’, ‘pop’, ‘remove’, ‘symmetric_difference’, ‘symmetric_difference_update’, ‘union’, ‘update’]
The output shows all the methods that can be used on sets. I will be demonstrating a few of them further in this article.
1) Finding the Length of a Set
To find the length of a set in Python, you can use the len() function. This function takes the name of the set as a parameter and returns an integer value which is equal to the number of elements present in the set.
Example: My_Set={1,’s’,7.8}
len(My_Set)
As you can see in the above output, 3 has been returned which equal to the number of elements present in My_Set. Now, these elements can be accessed as well, which is shown below.
2) Accessing Elements of a Set
Set elements cannot be accessed using the index numbers because, as specified before, elements of a set are not indexed. Therefore, when you want to access elements of a set, you can loop through it and access its elements.
Example: My_Set={1,’s’,7.8}
for x in My_Set:
print(x)
Output: S
1
7.8
As you can see in the output, the order is different than the order of elements supplied to the set. This is because the elements are not ordered.
3) Adding elements to a Set:
Elements can be added to a set using two functions, the add() and the update() function.
The add() function adds one element to the existing set as shown below:
Example: My_Set={1,’s’,7.8}
My_Set.add(3)
My_Set
Output:{1, 3, 7.8, ‘s’}
The update() function is used when you want to add more than one element to the existing set.
Example: My_Set={1,’s’,7.8}
My_Set.update([2,4.6,1,’r’])
My_Set
Output:{1, 2, 4.6, 7.8, ‘r’, ‘s’}
As you can see in the above output, the update() function is taking a list of 4 values and all values except 1 are added to My_Set. This is because 1 is already present in the set and therefore, it cannot be added again.
4) Removing Elements of a Set
To remove elements from a set, you can use either the remove(), discard() and the pop() functions.
The remove() function takes one parameter which is the item to be removed from the set.
Example: My_Set={1, 2, 4.6, 7.8, ‘r’, ‘s’}
My_Set.remove(2)
print(My_Set)
Output:{1, 4.6, 7.8, ‘r’, ‘s’}
As you can see, 2 has been removed from the set using the remove() function. In case you specify some element as a parameter to remove() that does not exist in the set, it will throw an error.
Now, if you want to remove some element from the set, and if you are not sure whether that element is actually present in the set or not, you can use the discard() function. This function will take the element to be removed from the set as a parameter but in case the element is not present, it does not throw an error.
Example: My_Set={1, 2, 4.6, 7.8, ‘r’, ‘s’}
My_Set.discard(4.6)
My_Set.discard(‘i’)
print(My_Set)
Output:{1, 2, 7.8, ‘r’, ‘s’}
The above output shows that 4.6 has been removed from My_Set but discard() has not thrown an error when I used My_Set.discard(‘i’) even though ‘i’ is not present in my set.
The pop() function also removes set elements, but since a set is unordered, you will not know which element has been removed.
Example: My_Set={1, 2, 4.6, 7.8, ‘r’, ‘s’}
My_Set.pop()
print(My_Set)
Output:{2, 4.6, 7.8, ‘r’, ‘s’}
The output shows that, using pop() some random element has been removed, which in this case is 1.
Now, in case you want to delete all elements present in a set, you can use the clear() method.
Example: My_Set={1, 2, 4.6, 7.8, ‘r’, ‘s’}
My_Set.clear()
print(My_Set)
Output: set()
As you can see in the above output, My_Set is an empty set.
In case you want to completely delete the set, you can use the del keyword.
Example: My_Set={1, 2, 4.6, 7.8, ‘r’, ‘s’}
del My_Set
print(My_Set)
When you run the above code, it will throw an error because My_Set is deleted.
You can also perform the various mathematical operations on a set such as a union, intersection, difference, etc which is discussed below.
5) Union of Sets
Union of sets refers to the concatenation of two or more sets into a single set by adding all unique elements present in both sets. This can be done in two ways:
 Using pipeline
 Using union() function

Using pipeline symbol:
Two sets can be concatenated using the  symbol as follows:
Example: a={1, 2, 4.6, 7.8, ‘r’, ‘s’}
b={2,5,’d’,’abc’}
c=ab
print(ab)
Output: {1, 2, 4.6, 5, 7.8, ‘r’, ‘abc’, ‘s’, ‘d’}
As you can see, in the above output, a union of set a and set b is stored in a new set c. You can concatenate more than two sets as well using  symbol.
Example: a={1, 2, 4.6, 7.8, ‘r’, ‘s’}
b={2,5,’d’,’abc’}
c={2,3,4,5}
d=abc
print(d)
Output: {1, 2, 3, 4, 4.6, 5, 7.8, ‘abc’, ‘d’, ‘r’, ‘s’}

Using the union() method:
To concatenate two or more sets, you can use the union() method as follows:
Example: a={1, 2, 4.6, 7.8, ‘r’, ‘s’}
b={2,5,’d’,’abc’}
c={‘m’,23,76,4.7}
print(“Set a U b = “,a.union(b))
print(“Set a U b U c = “,a.union(b,c))
Output: Set a U b = {1, 2, 4.6, 5, 7.8, ‘r’, ‘abc’, ‘s’, ‘d’}
Set a U b U c = {1, 2, 4.6, 5, 4.7, 7.8, ‘r’, 76, 23, ‘abc’, ‘m’, ‘s’, ‘d’}
The above output shows that the d is a union of sets a, b and c.
6) Intersection of Sets
The intersection of two or more sets is a new set consisting of only the common elements present in those sets.
This can be done in two ways:
 Using ‘&’ symbol
 Using intersection() function

Using ‘&’ symbol:
You can determine the intersection of two or more sets using the ‘&’ symbol as follows:
Example: a={1, 2,5, 4.6, 7.8, ‘r’, ‘s’}
b={2,5,’d’,’abc’}
c={2,3,4,}
print(a&b)
print(a&b&c)
Output: {2, 5}
{2}
The above output shows the union of sets a,b and c.

Using intersection() function:
You can determine the intersection of two or more sets using the intersection() function as follows:
Example: a={1, 2,5, 4.6, 7.8, ‘r’, ‘s’}
b={2,5,’d’,’abc’}
c={2,3,4}
print(“Set a intersection b = “,a.intersection(b))
print(“Set a intersection b intersection c = “,a.intersection(b,c))
Output: Set a intersection b = {2, 5}
Set a intersection b intersection c = {2}
The above output shows the intersection of sets a, b and c.
7) Difference of Sets:
The difference of sets produces a new set consisting of elements that are present only in one of those sets. This means that all elements except the common elements of those sets will be returned.
This can be done in two ways:
 Using the ‘‘ symbol
 Using difference() function

Using the ‘‘ symbol:
To find the difference of two sets using ‘‘ symbol, you can do as follows:
Example: a={1, 2,5, 4.6, 7.8, ‘r’, ‘s’}
b={2,5,’d’,’abc’}
c={2,3,4}
print(abc)
Output: {1, 4.6, 7.8, ‘r’, ‘s’}
The output consists of all elements of set ‘a’ except those that are present in ‘b’ and ‘c’.
 Using the difference() function:
The difference of sets can be determined using the builtin difference() function as follows:
Example: a={1, 2,5, 4.6, 7.8, ‘r’, ‘s’}
b={2,5,’d’,’abc’}
c={2,3,4}
print(“Set a – b = “,a.difference(b))
print(“Set a – b – c = “,a.difference(b,c))
Output: Set a – b = {1, 4.6, 7.8, ‘r’, ‘s’}
Set a – b – c = {1, 4.6, 7.8, ‘r’, ‘s’}
The above output is the result for difference using the difference() function.
Now what if you do not want to change the elements of your set at all, you can make use of frozen sets which is discussed below.
What is a frozen set?
A frozen set in Python is a set whose values cannot be modified. This means that it is immutable unlike a normal set which I have discussed previously. Frozen sets help serve as a key in dictionary keyvalue pairs.
1) How to create frozen sets?
Frozen sets can be obtained using the frozenset() method. This function takes any iterable items and converts it to immutable.
Example: a={1, 2,5, 4.6, 7.8, ‘r’, ‘s’}
b=frozenset(a)
print(b)
Output: frozenset({1, 2, 4.6, 5, 7.8, ‘r’, ‘s’})
The above output consists of set b which is a frozen version of set a.
2) Accessing Elements of a Frozen Set
Elements of a frozen set can be accessed by looping through it as follows:
Example: b=frozenset([1, 2, 4.6, 5, 7.8, ‘r’, ‘s’])
for x in b:
print(x)
Output: 1
2
4.6
5
7.8
s
The above output shows that using the for loop, all elements of the frozen set b have been returned one after the other.
Frozen sets are immutable, therefore, you cannot perform operations such as add(), remove(), update(), etc.
Hope you are clear with all that has been shared with you in this tutorial. This brings us to the end of our article on Sets in Python. Make sure you practice as much as possible and revert your experience.
Till then, Stay Safe, Stay Happy & Keep Coding…
IF YOU WANT TO KNOW ABOUt DATA SCIENCE click here.
CONNECT WITH THE AUTHOR ON LINKEDIN.
VISIT OUR WEBSITE BRIGHTERBEES FOR MORE INTERESTING STUFFS ABOUT LEARNING.
0 Comments