Python Set
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.
In this module, we will learn all about sets in order to get started with them. Following is the list of all topics that we will be covering.
So, without any further delay, let’s get started.
Instantiate a Set in Python
- Using commas to separate and curly braces to group elements
myset = {“apple”, “banana”, “cherry”}
print(myset)
Output:
{‘cherry’, ‘banana’, ‘apple’}
- Using the in-built set() method with the elements that we want to add as the parameters
myset = set((“apple”, “banana”, “cherry”)) # note the double round-brackets
print(myset)
Output:
{‘cherry’, ‘banana’, ‘apple’}
Remember that once a set is created we can’t change that set. We can only add elements. We can remove and then add elements but cannot change the existing elements. Now, let us see how to add items in a Python set.
Python Set operations
Adding Elements to a Set in Python
- Using the add() method with the element as the parameter:
myset = {“apple”, “banana”, “cherry”}
myset.add(“orange”)
print(myset)
Output:
{‘cherry’, ‘orange’, ‘banana’, ‘apple’}
- Using update()
myset = {“apple”, “banana”, “cherry”}
myset.update([“orange”, “mango”, “grapes”])
print(myset)
Output:
{‘cherry’, ‘mango’, ‘banana’, ‘apple’, ‘orange’, ‘grapes’}
Removing elements from sets in Python
Remove operation can be performed by using the following methods.
- Using the remove() method:
myset = {“apple”, “banana”, “cherry”}
myset.remove(“banana”)
print(myset)
output:
{‘cherry’, ‘apple’}
Note: If the item to be removed does not exist, remove() will raise an error.
2. Using discard():
myset = {“apple”, “banana”, “cherry”}
myset.discard(“banana”)
print(myset)
Output:
{‘cherry’, ‘apple’}
Note: If the item to be removed does not exist, discard() will not raise an error.
3. Using pop():
Remember that pop() will remove the last item of a set. Since sets are unordered, we should avoid performing pop() in sets.
myset = {“apple”, “banana”, “cherry”}
x = myset.pop()
print(x)
print(myset)
Output:
{‘banana’, ‘apple’}
Printing the Length of a Set in Python
To print the length of a set, we can simply use the in-built len() method as shown below:
myset = {“apple”, “banana”, “cherry”}
print(len(myset))
Output:
3
Emptying a Python Set Completely
To clear a set completely, we can use either the clear() method or the del() method.
- Using clear():
myset = {“apple”, “banana”, “cherry”}
myset.clear()
print(myset)
- Using del():
myset = {“apple”, “banana”, “cherry”}
del myset
print(myset)
Output:
Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘myset’ is not defined
As discussed above, sets in Python are used to carry out mathematical set operations such as union, intersection, etc. Let’s see a few examples of these mathematical operations.
Sets Union
To perform union, we use “|” operator. We can also use an in-built method called union(), which will give the same result.
The result of the union of two sets, say Set A and Set B, is a set containing the elements of both sets.
The following code block shows the union of Set A and Set B:
Set_A = {1,2,3,4,5}
Set_B = {4,5,6,7}
print(Set_A | Set_B)
Output:
{1, 2, 3, 4, 5, 6}
Set Intersection
To perform an intersection, we use ‘&’ operator. We can also use the in-built Python Function named intersection() to get the same result.
The intersection of two sets say Set A and Set B, can result in a set that contains the elements that are common in both sets, that is, the overlapping part in the diagram below.
The following code block shows the union of Set A and Set B:
Set_A = {1,2,3,4,5}
Set_B = {4,5,6,7}
print (Set_A & Set_B)
Output:
{4, 5}
Common Python Set functions
Method |
Description |
update() |
It updates a set with the union of this set and others. |
add() |
It adds an element to a set. |
clear() |
It removes all elements from a set. |
copy() |
It returns a copy of a set. |
difference() |
It returns a set containing the difference between two or more sets. |
difference_update() |
It removes the items in a set that are also included in another, specified set. |
discard() |
It removes a specified item. |
remove() |
It removes a specified element. |
pop() |
It removes an element from a set. |
intersection() |
It returns a set, that is the intersection of two other sets. |
intersection_update() |
It removes items in a set that are not present in another, specified set(s). |
isdisjoint() |
It returns whether two sets have an intersection or not. |
issubset() |
It returns whether another set contains a specific set or not. |
issuperset() |
It returns whether a set contains another set or not. |
symmetric_difference() |
It returns a set with the symmetric differences of two sets. |
union() or | |
It returns a set containing the union of sets. |
intersection or & |
It returns a set comprising common elements in two sets. |
Get 100% Hike!
Master Most in Demand Skills Now!
Frozenset in Python
frozenset() is an inbuilt Python function that takes an iterable object as input and makes it immutable. It Simply freezes the iterable objects and makes them unchangeable. The frozenset() function returns an unchangeable frozenset object (which is like a set object, only unchangeable).
In Python, frozenset() is the same as set except the forzensets are immutable which means that elements from the frozenset cannot be added or removed once created. This function takes input as any iterable object and converts them into an immutable object. The order of elements is not guaranteed to be preserved.
mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
print(x)
The output will be
frozenset({'cherry', 'banana', 'apple'})
Python Ordered Set
There aren’t ordered sets in Python, but programmers can use collections.OrderedDict from the Python standard library with just keys and the values as none.
OrderedSet([1, 2, 3])
Difference between set and list in Python
Set |
List |
Sets are mutable |
Lists are immutable |
Sets are unordered collections of items |
Lists are ordered collections of items |
Items can’t be replaced or changed. |
Items can be changed or replaced. |
Convert list to set in Python
list1 = [1, 2, 3, 3]
converted_set = set(list1)
print(converted_set)
The output will be
{1, 2, 3}
Convert set to list in Python
To convert a set to a list in python, you can typecast using the list(set_name) method.
Type Casting to list can be done by simply using list(set_name).
set1 = {‘Intellipaat’, ‘Python’, ‘Tutorial’}
list1 = list(set1)
print(list1)
[‘Intellipaat’, ‘Python’, ‘Tutorial’]
With this, we come to the end of this module in Python Tutorial. Now, if you are interested in knowing why Python is the most preferred language for data science, you can go through this blog on Python Data Science tutorial.
Further, check out our Python course for certification and prepare to excel in your career with our free Python developer interview questions listed by the experts.