Set operations in Python

In this tutorial, we are going to learn Set operation in Python.

We will learn some important functions of set operations in Python.

What is a set in Python?

The set in Python is an unordered collection of data that is unique, and the elements of a set are immutable.

Example code to declare a set in Python.

# set of integers
S = {1, 2, 3,5,6,7,8,9,0,10}
print(S)

Output:-

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

Operations of set

1) S.update( par ):-   This function will return the set S with the element added from set par.

S = {1, 2, 3,5,6,7,8,9,0,10}
print(S)

par= {12,11}

S.update(par)

print('after update S is ',S)

Output:-

{0, 1, 2, 3, 5, 6, 7, 8, 9, 10}
after update S is  {0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12

2) S.add( el ):-   This function will return the set S with added element el.

S = {1, 2, 3,5,6,7,8,9,0,10}
print(S)


S.add(13)

print('after adding 13 to S is ',S)

Output:-

{0, 1, 2, 3, 5, 6, 7, 8, 9, 10}
after adding 13 to S is  {0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 13}

3) S.remove( re ):-   This function will remove element re from set S if the element re is not present in the set then it will throw KeyError.

S = {1, 2, 3,5,6,7,8,9,0,10}
print(S)


S.remove(0)

print('after removing 13 from S is ',S)

Output:-

{0, 1, 2, 3, 5, 6, 7, 8, 9, 10}
after removing 13 from S is {1, 2, 3, 5, 6, 7, 8, 9, 10}

4) len( S ):-   This function will return the length of the set means the count of the number of the element present in the set.

S = {1, 2, 3,5,6,7,8,9,0,10}
print(S)

L= len(S)
print('the length of set is ' ,L)

Output:-

{0, 1, 2, 3, 5, 6, 7, 8, 9, 10}
the length of set is 10

5) S.issubset(par1):-   This function will test whether the set S is a subset of par1 or not.

S = {1,2,3,5,6,7,8,9,0,10}
print(S)

par1 = {1,2,3,4}

print(S.issubset(par1))

Output:-

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

6) S.issuperset(par2):-   This function will test whether the set S is a superset of par2 or not.

S = {1,2,3,4,5,6,7,8,9,0,10}
print(S)

par2 = {1,2,3,4}

print(S.issuperset(par2))

Output:-

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

7) S.union(par3):-   This function will return the union of set S and set par3.

S = {1,2,3,4,5,6,7,8,9,0,10}
print(S)

par3 = {12,34}

Ns = S.union(par3)
print('the new set is ' , Ns)

Output:-

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
the new set is  {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 34, 12}

 

Also, read: How to access items of Python sets

Leave a Reply

Your email address will not be published. Required fields are marked *