Set in Python

What is Set ?

In one line we can define it as, sets are unordered collection of unique elements.

  • In set, element's order are undefined.

  • Set has only unique elements, means we can't add duplicate element in set.

  • Sets are mutable object.

  • Though set is mutable object itself, but set can't have mutable type of objects like list, ,set, or dictionary

    as its element.

Set can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set can't have a mutable element, like list, set or dictionary, as its element.

How to create Set ?

Set can be created by placing sequence of values separated by 'comma' ( , ) within the curly { } bracket, or by using set( ) function.

# set of integers
my_set = {1, 2, 3}

{1, 2, 3}

# set of mixed datatypes
my_set = {1.0, "Prowess", (1, 2, 3)}

{1.0, 'Prowess', (1, 2, 3)}

# using set() function
my_set = set("Prowess")

{'s', 'o', 'e', 'w', 'P', 'r'}
#as we can see elements are unordered
#It also does not contain duplicate elements
#In the above output we can see 's' is 1 time only

Creating an empty set :

Empty set can be created by only using set( ) function.

#creating empty set
my_set = set()
print(type(my_set))  # < class 'set'>

#using empty curly bracket { } 
#will not create empty 'set', it will create
#empty 'dictionary'.

a = {}
print(type(a))  # < class 'dict'>

NOTE : Since sets are unordered, index has no meaning. So, We cannot access or change an element of set using indexing or slicing. Set does not support it.

my_set = {1, 2, 3}

Traceback (most recent call last):
  File "< pyshell#17>", line 1, in < module>
TypeError: 'set' object does not support indexing


Update a set in Python:

By using add( ), and update( ) function we can add new elements.

add( ) function adds a single element.

update( ) function adds multiple elements at a time.

Example :

my_set = {1,2,3}

{1, 2, 3, 4}

# add multiple elements

# Duplicate element discard
{1, 2, 3, 4, 5, 6}

# add list and set

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Remove element from a set in Python:

By using discard( ), and remove( ) function we can remove a particular element from set.

The only difference between discard( ), and remove( ) is that, discard( ) remove an element from set if it is a member. (Do nothing if the element is not in the set), while remove( ) remove an element from a set, if the element is not a member, raise a KeyError.

Example :

>>>my_set = {5,10,2,25,20}
>>> print(my_set)
{2, 5, 10, 20, 25}

#Discard element
>>> my_set.discard(10)
>>> print(my_set)
{2, 5, 20, 25}

#discard element not in set
>>> my_set.discard(100)
>>> print(my_set)
{2, 5, 20, 25}

#Remove element
>>> my_set.remove(20)
>>> print(my_set)
{2, 5, 25}

#Remove element not in set
>>> my_set.remove(200)
Traceback (most recent call last):
  File "< pyshell#37>", line 1, in < module>
KeyError: 200    

There are more functions like pop( ) and clear( ), which we can use to remove element from a set.

pop( ), remove and return an arbitary set element. Raise KeyError if the set is empty.

clear( ), removes all elements from a set.

Example :

>>>my_set = {5,10,2,25,20}
>>> print(my_set)
{2, 5, 10, 20, 25}

#pop an element
# random output
>>> my_set.pop()
>>>2    #in my case it gives 2

#clear the set
>>> my_set.clear()
>>> print(my_set)

#pop an element
#set is empty
>>> my_set.pop()
Traceback (most recent call last):
  File "< pyshell#51 >", line 1, in < module >
KeyError: 'pop from an empty set'

More Methods :

all()Returns true if all element are true or if set is empty.
any()return true if any element of the set is true. if set is empty, return false.
len()Returns length of the set or size of the set.
max()return largest item in the given set.
min()return minimum element of given set.
sum()Sums up the numbers in the set.
sorted()Return a new sorted list from elements in the set(does not sort the set itself).

Program to understand the functions :

>>> my_set = {10,20,30,40,10,10}
>>> print(all(my_set))
>>> print(any(my_set))
>>> print(len(my_set))
>>> print(max(my_set))
>>> print(min(my_set))
>>> print(sum(my_set))
>>> print(sorted(my_set))
[10, 20, 30, 40]


Set can be used for mathematical set operations like union, intersection, difference etc. We can perform these operations by using methods or operators.

set1.union(set2)set1|set2Returns a set which is the union of sets set1 and set2.
set1.update(set2)set1|=set2Adds all elements of array set2 to the set set1.
set1.intersection(set2)set1&set2Returns a set which is the intersection of sets set1 and set2.
set1.intersection_update(set2)set1&=set2Update the set1 with the intersection of itself and another.
set1.difference(set2)set1 - set2Returns the set difference of set1 and set2 (the elements included in set1, but not included in set2).
set1.difference_update(set2)set1-=set2Removes all elements of set2 from the set set1.
set1.symmetric_difference(set2)set1^set2Returns new set with elements in either set1 or set2 but not both.
set1.symmetric_difference_update(set2)set1^=set2Update set1 with elements from set1 or set2 but not both.
set1.issubset(set2)set1<=set2Test whether every element in set1 is in set2, and returns true otherwise false.
set1.issuperset(set2)set1>=set2Test whether every element in set2 is in set1, and returns true otherwise false.
set1.isdisjoint(set2)Return True if two sets have a null intersection.
check proper subsetset1<set2Return True if set1 is proper subset of set2.
check proper supersetset1>set2Return True if set1 is proper superset of set2.
check equalset1=set2Return True if set1 is equivalent to set2.

Code Snippet to illustrate all Set operations in Python

# Creating two sets
set1 = set()
set2 = set()
# Adding elements to set1
for i in range(1, 6):
# Adding elements to set2 
for i in range(3, 8): 
print("Set1 = ", set1)
print("Set2 = ", set2) 

# Union of set1 and set2
set3 = set1 | set2# set1.union(set2)
print("Union of Set1 and  Set2: Set3 = ", set3)
# Intersection of set1 and set2 
set4 = set1 & set2# set1.intersection(set2) 
print("Intersection of Set1 & Set2: Set4 = ", set4) 
# Checking relation between set3 and set4 
if set3 > set4: # set3.issuperset(set4) 
    print("Set3 is superset of Set4") 
elif set3 < set4: # set3.issubset(set4) 
    print("Set3 is subset of Set4") 
else : # set3 == set4 
    print("Set3 is same as Set4") 
# displaying relation between set4 and set3 
if set4 < set3: # set4.issubset(set3) 
    print("Set4 is subset of Set3") 
# difference between set3 and set4 
set5 = set3 - set4 
print("Elements in Set3 and not in Set4: Set5 = ", set5) 
# checkv if set4 and set5 are disjoint sets 
if set4.isdisjoint(set5): 
    print("Set4 and Set5 have nothing in common\n") 
# Removing all the values of set5 
print("After applying clear on sets Set5: ") 
print("Set5 = ", set5) 
Set1 =  {1, 2, 3, 4, 5}
Set2 =  {3, 4, 5, 6, 7}

Union of Set1 and  Set2: Set3 =  {1, 2, 3, 4, 5, 6, 7}
Intersection of Set1 & Set2: Set4 =  {3, 4, 5}

Set3 is superset of Set4
Set4 is subset of Set3

Elements in Set3 and not in Set4: Set5 =  {1, 2, 6, 7}

Set4 and Set5 have nothing in common

After applying clear on sets Set5: 
Set5 =  set()                    

Frozen Sets

  • Frozen sets are immutable objects, it has the characteristics of a set, but its elements cannot be changed once assigned.
  • The frozenset() is an inbuilt function in Python which takes an iterable objects as argument and make them immutable.

Use ?

Since sets are mutable objects and unhashable, they can't be used as keys in dictionary. But frozensets are hashable and can be used as key in dictionary data type.

Methods support by frozenset:

frozenset supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union() .

Frozenset doesn't support any method that update and remove elements.


# if no parameters are passed to forzenset()
# method, then it returns empty frozenset object.

>>> my_froset = frozenset()
>>> print(my_froset)


>>> my_froset1 = frozenset([1,2,3,4,2,6])
>>> print(my_froset1)

frozenset({1, 2, 3, 4, 6})

>>> my_froset1.add(10) # can not perform
Traceback (most recent call last):
  File "< pyshell#83 >", line 1, in < module >
AttributeError: 'frozenset' object has no attribute 'add'

Next chapter is Dictionary


Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at

Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at

(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016,, All rights reserved