Sets in Python

quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

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}
print(evenNumber)
stringAndNum = {"one", 2, 3}
print(stringAndNum)

Output:

{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'])
print(setWithMethod)

Output:

{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')
print(set(c))

Output:

{'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]}
print(mySetOne)
# This will work
mySetTwo = {1, 2, (3, 4)}
print(mySetTwo)

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}
initialSet.add(3)
print(initialSet)
toAdd = [4, 5]
initialSet.update(toAdd)
print(initialSet)

Output:

{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)
mySet.remove(3)
print("After: ", mySet)
mySet.discard(4)
print("Using discard: ", mySet)
mySet.clear()
print(mySet)

Output:

Before: {1, 2, 3, 5}
After: {1, 2, 5}
Using: {1, 2, 5}
set()

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

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)
print(budgetCars.union(highEndCard))

Ouput:

{'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

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)
print(chemicalOne.intersection(chemicalTwo))

Output:

{'Cl'}
{'Cl'}

Difference

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(easyToLearn.difference(hardToLearn))
print('Changing order we get: ')
print(hardToLearn - easyToLearn)
print(hardToLearn.difference(easyToLearn))

Output:

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

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)
print(a.symmetric_difference(b))

Output:

{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'])
print(a)

Output:

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)
print(setOfDict)

Output:

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.

Conclusion

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.

Challenge Time!
quiz
quiz
Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.
Free Courses by top Scaler instructors
certificate icon
Certificates
Python Tutorial
This program includes modules that cover the basics to advance constructs of Python Tutorial. The highly interactive and curated modules are designed to help you become a master of this language.'
If you’re a learning enthusiast, this is for you.
Module Certificate
Criteria
Upon successful completion of all the modules in the hub, you will be eligible for a certificate.
You need to sign in, in the beginning, to track your progress and get your certificate.
rcbGet a Free personalized Career Roadmap from