Python Sets
A set is a data structure in Python that is unordered and unindexed. It does not allow duplicate elements. Sets are written with curly brackets { }.
Each element in a set is unique and must be immutable. However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, difference etc. We can do this with operators or methods.
Sets are unordered, so the elements of a set will appear in a random order.
Several operations may be performed on a Python set:~
1) Creation of a set:
To create a set in Python we have to put different comma-separated values between curly brackets { }. It is also possible to use the set() constructor with double round-brackets to make a set. See the code below:
# set01.py
A = {10, 20, 30, 40, 50}
print(A)
B = set((30, 50, 60, 70))
print(B)
Output:
{40, 10, 50, 20, 30}
{70, 50, 60, 30}
2) Accessing elements of a set:
We cannot access elements in a set by using an index, since sets are unordered the elements has no index. However, we can loop through the set elements using a for loop, or inquire about a specific value is present in a set or not, by using the ‘in’ keyword. See the codes below with output:
# set02.py
A = {10, 20, 30, 40, 50}
for item in A:
print(item)
Output:
40
10
50
20
30
Checking if elements 10 and 70 are present in the given set:
# set03.py
A = {10, 20, 30, 40, 50}
print(10 in A)
print(70 in A)
Output:
True
False
3) Changing element of a set:
It is not possible to change the element of a set. However, we can add new items.
4) Length of a set:
It is easier to count the number of elements in a set using the len() method:
# set04.py
A = {10, 20, 30, 40, 50}
print(len(A))
Output:
5
5) Add elements to a set:
We can use the add() method to add a single element to the set or add multiple elements using the update() method. The update() method can take lists, tuples, strings or other sets as its argument. In all cases, duplicate elements are avoided. See the code below:
# set05.py
A = {10, 20, 30, 40, 50}
A.add(60)
print(A)
B = {60, 70, 80}
B.update([80, 90])
print(B)
Output:
{40, 10, 50, 20, 60, 30}
{80, 90, 60, 70}
6) Remove element from a set:
There are various methods to remove elements from a set.
We can use the remove() or discard() method to delete a specific item from the set. The difference between them is that if the element to remove does not exist, remove() will raise an error; whereas, the item to remove does not exist, discard() will not raise any error.
A = {10, 20, 30, 40, 50}
A.remove(30)
print(A)
A.remove(20)
print(A)
Output:
{40, 10, 50, 20}
{40, 10, 50}
The pop() method removes the last element from the set. Sets are unordered, so when we use this method, we will not know which element gets removed. Basically, the return value of the method is the removed item. See below:
# set07.py
A = {10, 20, 30, 40, 50}
k = A.pop()
print(k)
print(A)
Output:
40
{10, 50, 20, 30}
Using ‘del’ keyword we can delete the set completely:
# set08.py
A = {10, 20, 30, 40, 50}
del A
print(A) # will create an error
Output:
ERROR
The clear() method makes the set empty:
# set09.py
A = {10, 20, 30, 40, 50}
A.clear()
print(A)
Output:
set()
7) Set Union:
Union of A and B is a set of all elements from both sets. Union operation is performed using ‘|’ operator. Same can be done using the union() method:
# set07.py
A = {10, 20, 30, 40, 50}
B = {30, 50, 60, 70}
print(A | B)
print(B.union(A))
Output:
{50, 20, 70, 40, 10, 60, 30}
{70, 40, 10, 50, 20, 60, 30}
8) Set Intersection:
Intersection of A and B is a set of elements that are common in both sets. Intersection operation is performed using ‘&’ operator. Same can be done using intersection() method:
# set08.py
A = {10, 20, 30, 40, 50}
B = {30, 50, 60, 70}
print(A & B)
# print(A.intersection(B))
Output:
{50, 30}
9) Set Difference:
Difference of A and B is a set of elements denoted by (A-B) that are only in A but not in B. Similarly, (B-A) is a set of element in B but not in A.
Difference operation is performed using ‘-‘ operator. Same can be done using difference() method:
# set09.py
A = {10, 20, 30, 40, 50}
B = {30, 50, 60, 70}
print(A - B)
# print(A.difference(B))
print(B - A)
# print(B.difference(A))
Output:
{40, 10, 20}
{60, 70}
10) Set Symmetric Difference:
Symmetric difference of A and B is a set of elements in both A and B except those that are common in both. This operation is performed using ‘^’ operator. Same can be done using symmetric_difference() method:
# set10.py
A = {10, 20, 30, 40, 50}
B = {30, 50, 60, 70}
print(A ^ B)
# print(A.symmetric_difference(B))
Output:
{70, 40, 10, 20, 60}
11) Set Comparison:
We can check if a given set is a subset or superset of another set. The result is True or False depending on the elements present in the sets. See the example below:
# set14.py
A = {10, 20, 30, 40, 50}
S = {20, 30, 50}
sub = S <= A # checking whether S is a subset of A
super = A >= S # checking whether A is a superset of S
print(sub)
print(super)
Output:
True
True
12) Creating Frozen Set:
Frozen set is a new type of set in Python that has the characteristics of a set, but its elements cannot be changed once assigned. While tuples are immutable lists, frozen sets are immutable sets. They are hashable and can be used as keys to a dictionary.
Frozen set can be created using the function frozenset(). It supports methods like union()
, intersection()
, difference()
, symmetric_difference()
, isdisjoint()
, issubset()
, issuperset()
, and
copy()
. Being immutable it does not have method that can add or remove elements. See the example below:
# set15.py
A = frozenset([10, 20, 30, 40, 50])
print(A)
# A.add(90) # cannot be done
B = frozenset([30, 50, 60, 70])
print(B)
print(A.union(B))
print(A.intersection(B))
print(A.difference(B))
print(A.symmetric_difference(B))
Output:
frozenset({40, 10, 50, 20, 30})
frozenset({70, 50, 60, 30})
frozenset({50, 20, 70, 40, 10, 60, 30})
frozenset({50, 30})
frozenset({40, 10, 20})
frozenset({70, 40, 10, 20, 60})