Python Sets
Python Sets
Python Sets
A Set in Python programming is an unordered collection data type that is iterable, mutable and has
no duplicate elements.
Set are represented by { } (values enclosed in curly braces)
The major advantage of using a set, as opposed to a list, is that it has a highly optimized method
for checking whether a specific element is contained in the set. This is based on a data structure
known as a hash table. Since sets are unordered, we cannot access items using indexes as we do
in lists.
Example of Python Sets
Python3
type(var)
Output:
set
Time Complexity: O(1)
Auxiliary Space: O(1)
Python3
print(myset)
myset.add("d")
print(myset)
Output:
Python set is an unordered datatype, which means we cannot know in which order the elements of
the set are stored.
{'c', 'b', 'a'}
{'d', 'c', 'b', 'a'}
Time Complexity: O(n)
Auxiliary Space: O(n)
Python sets cannot have a duplicate value and once it is created we cannot change its value.
Python3
print(myset)
myset[1] = "Hello"
print(myset)
Output:
The first code explains that the set cannot have a duplicate value. Every item in it is a unique
value.
The second code generates an error because we cannot assign or change a value once the set is
created. We can only add or delete items in the set.
{'Geeks', 'for'}
TypeError: 'set' object does not support item assignment
Heterogeneous Element with Python Set
Python sets can store heterogeneous elements in it, i.e., a set can store a mixture of string,
integer, boolean, etc datatypes.
Python3
print(myset)
Output:
{True, 10, 'Geeks', 52.7, 'for'}
Time Complexity: O(n)
Auxiliary Space: O(n)
Python
print(normal_set)
# A frozen set
print("\nFrozen Set")
print(frozen_set)
# frozen_set.add("h")
Output:
Normal Set
{'a', 'c', 'b'}
Frozen Set
{'e', 'g', 'f'}
Time Complexity: O(n)
Auxiliary Space: O(n)
Insertion in the set is done through the set.add() function, where an appropriate record value is
created to store in the hash table. Same as checking for an item, i.e., O(1) on average. However,
in worst case it can become O(n).
Python3
# A Python program to
# in a set
# Creating a Set
print(people)
# in the set
people.add("Daxit")
print(people)
Output:
People: {'Idrish', 'Archi', 'Jay'}
Two sets can be merged using union() function or | operator. Both Hash Table values are
accessed and traversed with merge operation perform on them to combine the elements, at the
same time duplicates are removed. The Time Complexity of this is O(len(s1) + len(s2)) where s1
and s2 are two sets whose union needs to be done.
Python3
# Python Program to
# demonstrate union of
# two sets
# function
population = people.union(vampires)
print(population)
# operator
population = people|dracula
print(population)
Output:
Union using union() function
{'Karan', 'Idrish', 'Jay', 'Arjun', 'Archil'}
This can be done through intersection() or & operator. Common Elements are selected. They are
similar to iteration over the Hash lists and combining the same values on both the Table. Time
Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets whose union needs to
be done.
Python3
# Python program to
# demonstrate intersection
# of two sets
set1 = set()
set2 = set()
for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)
# Intersection using
# intersection() function
set3 = set1.intersection(set2)
print(set3)
# Intersection using
# "&" operator
print(set3)
Output:
Intersection using intersection() function
{3, 4}
To find differences between sets. Similar to finding differences in the linked list. This is done
through difference() or – operator. Time complexity of finding difference s1 – s2 is O(len(s1))
Python3
# Python program to
# demonstrate difference
# of two sets
set1 = set()
set2 = set()
for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)
set3 = set1.difference(set2)
print(set3)
print(set3)
Output:
Difference of two sets using difference() function
{0, 1, 2}
Python3
# Python program to
# demonstrate clearing
# of set
set1 = {1,2,3,4,5,6}
print("Initial set")
print(set1)
set1.clear()
Output:
Initial set
{1, 2, 3, 4, 5, 6}
x in s O(1) O(n)
replace “min”
O(min(len(s),
Intersection s&t O(len(s) * len(t)) with “max” if t is
len(t))
not a set
Multiple
(n-1)*O(l) where l is
intersection
max(len(s1),..,len(sn))
s1&s2&..&sn
s1 == s2 s1 is equivalent to s2
s1 != s2 s1 is not equivalent to s2
s1 <= s2 s1 is subset of s2
s1 >= s2 s1 is superset of s2
# initializing set
test_set = {6, 4, 2, 7, 9}
# internally reorders
test_set.update(up_ele)
# printing result
print("Set after adding elements : " + str(test_set))
Output:
The original set is : {2, 4, 6, 7, 9}
Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}
Using | Operator (Pipe Operator)
The pipe operator internally calls the union() function, which can be used to perform the task of
updating the Python set with new elements.
Python3
# initializing set
test_set = {6, 4, 2, 7, 9}
test_set |= set(up_ele)
# printing result
Output:
The original set is : {2, 4, 6, 7, 9}
Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}
Using List Comprehension
Here, we will use the Python list comprehension method to append only those elements in a set
that are not already present in it. Then we use the set() constructor to convert the list to a Python
set.
Python3
# initializing set
test_set = {6, 4, 2, 7, 9}
test_list = list(test_set)
# printing result
Output:
The original set is : [2, 4, 6, 7, 9]
Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}
Using reduce() Method
This approach uses the reduce() function from the functools module to apply a union operation
between each element of a list and the set, resulting in a new set in Python. The reduce() function
takes a lambda function and the union() function
Python3
# import functools
# initializing set
test_set = {6, 4, 2, 7, 9}
# printing result
Output:
The original list is : {2, 4, 6, 7, 9}
Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}
Return value : This method adds set2 to set1 and returns nothing.
Example of Python set update()
Python3
list1 = [1, 2, 3]
list2 = [5, 6, 7]
set1 = set(list2)
set2 = set(list1)
# Update method
set1.update(set2)
print(set1)
set1.update(list3)
print(set1)
Output :
{1, 2, 3, 5, 6, 7}
{1, 2, 3, 5, 6, 7, 10, 11, 12}
Python3
list1 = [1, 2, 3, 4]
list2 = [1, 4, 2, 3, 5]
set1 = set(list2)
set2 = set(list1)
# Update method
set1.update(set2)
print(set1)
set1.update(alphabet_set)
print(set1)
Output :
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 'c', 'b', 'a'}
Python3
number = {1, 2, 3, 4, 5}
Output:
Updated set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Input : set(['a','b','c','d','e'])
Output :
{'d', 'c', 'a', 'b'}
{'c', 'a', 'b'}
{'a', 'b'}
{'b'}
set()
Using the pop() method The pop() is an inbuilt method in Python that is used to pop out or
remove the elements one by one from the set. The element that is the smallest in the set is
removed first followed by removing elements in increasing order. In the following program, the
while loop goes onto removing the elements one by one, until the set is empty.
Python3
def Remove(initial_set):
while initial_set:
initial_set.pop()
print(initial_set)
# Driver Code
Remove(initial_set)
Output:
{9, 10, 12, 13, 15}
{10, 12, 13, 15}
{12, 13, 15}
{13, 15}
{15}
set()
Approach:
This approach removes the elements from the set using the discard() method.
Initialize a set my_set with the given elements.
Enter a loop that runs as long as there are elements in the set my_set.
Find the maximum element in the set using the max() function and remove it from the set using the
discard() method.
Print the updated set after each removal.
Exit the loop when the set my_set becomes empty.
Python3
while my_set:
my_set.discard(max(my_set))
print(my_set)
Output
for i in range(len(my_set)):
my_set.remove(next(iter(my_set)))
print(my_set)
Output
import random
# check 7058
print(7058 in data)
# check 7059
print(7059 in data)
# check 7071
print(7071 in data)
Output:
True
True
False
Method 2: Using not in operator
This is an membership operator used to check whether the given value is present in set or not. It
will return True if the given element is not present in set, otherwise False
Syntax:
element not in set
where,
set is an input set
element is the value to be checked
Example: Check if an element is present in a set
Python3
import random
# check 7058
# check 7059
# check 7071
Output:
False
False
True
Method 3: Using Counter() Function
Python3
freq = Counter(data)
# check 7058
print(7058 in freq.keys())
# check 7059
print(7059 in freq.keys())
# check 7071
print(7071 in freq.keys())
Output
True
True
False
Time Complexity:O(N)
Auxiliary Space: O(N)
# check 7058
# check 7059
# check 7071
Output
True
True
False
Time Complexity: O(n)
Auxiliary Space: O(1)