Search for Courses, Topics

Sets in Python

Learn about sets, set operations in Python.

16 Nov 2021-7 mins read

Introduction to Sets in Python

In mathematics, a set is a collection of distinct objects forming a group. The objects can be of any type like numbers, names of movies, company names, etc. There can be any number of objects in a set and the objects can be of different data types. Set is a concept of Set Theory which is a popular and useful topic of mathematics. There are several operations that can be performed on a set, these operations include union, intersection, difference.

Sets in python are also similar but with a few conditions.

  • First, that a set cannot contain duplicate elements.
  • Second, the elements of a set are immutable(once entered cannot be changed) but the set as a whole is mutable.

In python, operations like union, intersection can be performed on a set, but it is also used for other purposes which we will discuss in this article.

The formal definition of a set in Python will be: Set is an unordered collection of items, where every element is unique and immutable. However, the set itself is mutable.

Creating Sets in Python

Just like most other things, creating a set in Python is really simple. There are two ways of creating a set

  1. Putting all the elements inside curly braces “{“ and “}”
  2. Using set() method.

If the curly braces look familiar to you, it's because they are used in Python Dictionaries.

Using Curly Braces

Let's look at an example.

evenNumber = {2, 4, 6}
stringAndNum = {"one", 2, 3}


{2 , 4 , 6}
{2, 3, 'one'}

Here you can see we have created a set that contains only numbers and another which contains numbers and strings.

Using set() function

Syntax: set([iterable])

Return type: Empty is no argument is given otherwise a set or frozenset object

set() takes an iterable as an argument. In python, string, lists, and dictionaries are iterable so you can pass them inside set(). set() returns a set or frozenset object (explained later in the article). If there is no input (i.e. no iterable passed as argument) then an empty set is returned.

Here is an example which uses set() function

setWithMethod = set([1, 2, 'three'])


{1, 2, 'three'}

Here is a code example that shows how you can make a set from iterables (lists, dictionaries, string, etc.)

a = {"one": 1, "two": 2}
b = [100, 200, 300]
c = 'python'
print(set(a), end='\n')
print(set(b), end='\n')


{'one' , 'two'}
{200, 100, 300}
{'h', 'n', 'o', 'p', 'y', 't'}

One important property of set() is that the elements are immutable. So you cannot enter any mutable object inside a set (like dictionaries, lists, set).

# This wont work
mySetOne = {1, 2, [3, 4]}
# This will work
mySetTwo = {1, 2, (3, 4)}

Here when mySetOne is executed it gives TypeError: unhashable type: ‘list’

mySetOne = {1, 2, [3,4]}
TypeError: unhashable type: 'list'

When mySetTwo is executed, we get

{1, 2, (3,4)}

Adding Items in a Python Set

Adding elements in a set is not the same as adding elements in lists. Set do not use indexing. There are two methods to add elements in a set

  1. add() allows adding single element
  2. update() allows to add multiple elements

Let's take a look at the code -

initialSet = {1, 2}
toAdd = [4, 5]


{1, 2, 3}
{1, 2, 3, 4, 5}

update() takes an iterable like string, list, dictionary as an argument.

Removing Items from a Set in Python

For removing elements we have these methods:

  1. remove(element) - This method removes the element from the set. If the element is not present then it will throw an error.
  2. discard(element) - This method removes the element from the set. If the element is not present then the set will remain unchanged.
  3. clear() - This method is used to delete all the set elements.

Let’s take a look at the code to understand these method better.

mySet = {1, 2, 3, 5}
print("Before: ", mySet)
print("After: ", mySet)
print("Using discard: ", mySet)


Before: {1, 2, 3, 5}
After: {1, 2, 5}
Using: {1, 2, 5}

Here you can see that the element that is passed to discard() does not exist in the set and discard() did not give any error. Also, this code shows the use of clear().

Set Operations in Python

Most operations on set can be performed in two ways.

  1. Using operator
  2. Using methods

We will look at both ways of accomplishing the task.


Union operation combines all the elements from both sets. “|” (pipe) symbol is used to carry out this operation. We can also use the union() method.

Union Set Operation in Python

Lets look at the code example:

budgetCars = {'Maruti', 'Hyundai', 'Ford'}
highEndCard = {'Audi', 'BMW', 'Ford'}
print(budgetCars | highEndCard)


{'Hyundai' , 'Ford' , 'Audi' ,'Maruti' ,'BMW'}
{'Hyundai' , 'Ford' , 'Audi' ,'Maruti' , 'BMW'}

In this example, you can see that union combines all the elements from both sets and it does not include any duplicate elements.


Intersection operation picks the elements that are common in both sets. “&” operator or intersection() method is used to perform this operation.

Intersection Set Operation in Python

Here in the example, you can see that the intersection result picks the two elements which are common in both the chemicals.

chemicalOne = {'Na', 'K', 'Cl'}
chemicalTwo = {'HCL', 'Cl', 'Ba'}
print(chemicalOne & chemicalTwo)




The difference in sets is similar to subtraction. When set B is subtracted from set A i.e, Set A - Set B then we say that in the resulting set all the elements of Set B will be removed from Set A. “-” (subtraction sign) or difference() method is used to perform this operation.

Difference Set Operation in Python

easyToLearn = {'Python', 'JavaScript', 'C++'}
hardToLearn = {'Assembly', 'C++'}
print(easyToLearn - hardToLearn)
print('Changing order we get: ')
print(hardToLearn - easyToLearn)


{'JavaScript' , 'Python'}
{'JavaScript' , 'Python'}
Changing order we get :

Let's assume that you passed three sets A, B, and C to find the difference. In this case, first, the difference of A and B will be calculated, then its result (suppose R) will be used to calculate the difference with C.

Symmetric Difference

The symmetric difference of two sets A and B is a set that contains elements in either A or B but not both. “^” operator or symmetric_difference() method is used to perform this operation.

Symmetric Difference Set Operation in Python

a = {1, 2, 3}
b = {3, 4, 5}
print(a ^ b)


{1, 2, 4, 5}
{1, 2, 4, 5}

Frozen Set

Frozen set is a built-in data type in Python. It is a set that is immutable (once defined, cannot be changed). It supports all non-modifying operations of the set. Operations like add() won’t work in the case of a frozen set.

Here is a simple example:

a = frozenset(['one', 'two', 'three'])



A common use case of frozenset can be to store dictionary keys. Here is an example showing that

myDict = {'name': "Python", 'type': 'interpreted'}
setOfDict = frozenset(myDict)


frozenset({'name', 'type'})

Suppose that we want to display this data to some user then using the frozenset makes sense as no one will be able to change them.


In this article, you have gained knowledge of how to create sets in Python and perform various operations on it.

Set like lists, dictionaries are a data type given by Python which has its own use case. It might be helpful in some places while not so much in others. Knowing what you can do with a set will help to judge if it fits your requirement.

certificate icon
Python Tutorial
Module Certificate
You’ll be able to claim a certificate for any course you have access to only after you’ve spent enough time learning. The time required is determined by the length of the course.
Certificates are a fantastic way to showcase your hard-earned skills to employers, universities, and anyone else that may be interested. They provide tangible proof that you’ve completed a course on Scaler Topics. In many cases they can help you claim a training reimbursement or get university credit for a course.