Python Sets

What are Python Sets?

A Python set is a collection of unique elements which are not in any particular order. It is declared using comma-separated values within braces {}. It has been in Python since version 2.4. The common mathematics operations can be carried out on python sets, such as the intersection, difference, complement, and union of two sets. A Python set's elements can be Heterogenous or Homogenous. Since each element is unique in a Set, duplicate elements are automatically expunged. Python sets do not require indexing because of their unordered nature. The elements contained in the Set are in an immutable form, but the Set itself can be changed.

How to create Sets?

A Set in Python is created by putting all the elements of the Set separated by comma(",") and inside the curly brace("{}") or by using set(), one of Python's built-in functions.


Days = set(["Mercury",""Venus",""Earth",""Mars"]) 
Dates: {21,22,17} 
print (Months) 


my_set = {1,2,3,4,5} #creating a set



{1, 2, 3, 4, 5}

For creating an empty set, the procedure is a bit tricky. Normally you would assume that an empty set can be created simply by putting nothing inside the curly braces. But in Python, this syntax is used to create an empty dictionary.


my_set = {}


The set() function is used to create a emply set. Like this


my_set = {} #creates an empty dictionary
my_set = set() #creates an empty set



<class 'dict'> <class 'set'>

As you can see in the output, we created an empty dictionary by using the curly braces syntax. While the second method in which we used the Set() function is the actual syntax for creating an empty set.

Properties of Sets

Elements in the Set are always unique

Elements in a Set have to be unique. No duplicate elements.


my_set = {1,1,3,2,5,6,2} #creating a set with duplicate elements



{1, 2, 3, 5, 6}

As you can see in the output, the duplicates do not show up in the printed Set. This is because all the elements in the Set need to be unique. So they are automatically removed from the Set.

Sets are mutable but the elements need to be immutable

Although Sets themselves are mutable, the elements inside a Set cannot be immutable. This means we can not put a list, dictionary, or a Set inside a Set


my_set = {1,1,3,2,[1,61,2]} #creating a set with list as element

print(my_set) #will throw error

my_set = {1,1,3,2,{1,61,2}} #creating a set with set as element

print(my_set) #will throw error

my_set = {1,1,3,2,(1,61,2)} #creating a set with tuple as element

print(my_set) #will throw not error



TypeError: unhashable type: 'list' TypeError: unhashable type: 'set' {1, 2, 3, (1, 61, 2)}

As you can see, mutable objects like lists, dictionaries, sets etc. are not allowed to be put inside a set as elements.

Elements in a Set are unordered

There is no sequence by which the elements are stored inside a set. You cannot get an item in a set based on its index number and you can not change an item that is already in the Set. You also cannot perform any slicing operations on a set.


sample_set = {1,1,3,2,5}
print(sample_set[3]) #indexing is not allowed, will throw error



TypeError: 'set' object is not subscriptable

Find Length of the Sets

You can use len() to determine how many items are in a sets.

Adding Elements to Sets

Python sets are powerful objects, but it has few constraints. It can contain immutable object types only. Hence, lists and dictionaries cannot be embedded in sets. All types of variables like integer, float, string, etc. can be added to Sets, and to add compound values, you can use Tuples. While doing set operations, Tuples are compared by full values. If you add a duplicate element, it will not be added to the set

To add an element to a set, we use the add() method, or We can only add a single element using this function. Strings, lists, tuples, or other sets can be used as an argument when using the update() method. Iterable objects like Lists, Tuples, and Dictionaries cannot be added using this function.


planets = {"Mercury","Venus","Earth"}
planets.add("Mars") #will work for single element
planets.add(["Juipter","Saturn"]) #will throw error



{'Earth', 'Mercury', 'Mars', 'Venus'} Error

We can use the update() method. Adding multiple elements to a Sets can take iterable objects like lists as arguments.


planets = {"Mercury","Venus","Earth","Mars"}



{'Juipter', 'Venus', 'Mercury', 'Earth', 'Saturn', 'Mars'}

Removing elements from a Set

We use the remove() function to remove elements from a set. It takes precisely one argument. So you cannot remove multiple elements at the same time with this function.


planets = {"Mercury","Venus","Earth","Mars"}



{Mercury, Venus, Earth}

The discard() method can be used for element removal from a Python Set. It is different from remove() in the fact that it does not change the set when the element given as an argument to it is not present in the set. While the remove() method throws an error if an element does not exist in the set.


planets = {"Mercury","Venus","Earth","Earth","Mars"}



Traceback (most recent call last): File "<string>", line 4, in <module> KeyError: 'Jupiter' {'Venus', 'Mercury', 'Mars', 'Earth'}

The pop() function is also an option for removing elements from a Python set. Since the elements in the set are unordered, the element to be removed by pop() cannot be determined. It randomly picks an element from the set and removes it.


demo_set = {1,1,4,3,5}



{3, 4, 5}

To remove all the elements from the set, we use the clear() function.


planets = {"Mercury","Venus","Earth","Mars"}}




Sequential data types, e.g. lists, can be converted into sets using the set() function In the following small example, we define a list of planets that we convert into a set using the set() function:


planets_list = ["Mercury","Venus","Earth","Mars"]
planets_set = set(planets_list)



{'Earth', 'Venus', 'Mars', 'Mercury'}

The set function is often used to remove multiple occurrences from lists or other sequential data types.

Various Set Operations in Python

These are some of the operations that can be performed on Sets supported by Python:-

Operation Description
set1.union(set2) Returns the union of set1 and set2
set1.intersection(set2) Returns the intersection of set1 and set2
set1.difference(set2) Returns the difference of set1 and set2
set1.symmetric_difference(set2) Returns the symmetric difference of set1 and set2
set1.isdisjoint(set2) Returns True if set1 and set2 are disjoint Else returns False
set1.issubset(set2) Returns True if a set1 is subset of set2 Else returns False
set1.issuperset(set2) Returns True if a set1 is superset of set2 Else returns False