So, without any further delay, let’s get started.
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.
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’}
Become a Certified Python Programmer
Master Python Programming and Start Building Powerful Applications
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}
Master Data Science with Real-World Projects
Unlock Your Potential in Data Analysis, Modeling, and Visualization
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 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.
Our Python Courses Duration and Fees
Cohort starts on 14th Jan 2025
₹20,007