Set operations in Python

Nutan
5 min readApr 24, 2022

--

In this blog, we will learn set operations. We will see add(), remove(), update(), union(), intersection(), difference() and many more functions with examples.

Created by Nutan

What is set?

A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.

Like other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior. Set items can appear in a different order every time you use them, and cannot be referred to by index or key.

There are currently two built-in set types, set and frozenset.

The set type is mutable — the contents can be changed using methods like add() and remove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set.

The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

The constructors for both classes work the same:

class set([iterable]) class frozenset([iterable]) — Return a new set or frozenset object whose elements are taken from iterable.

Instances of set and frozenset provide the following operations:

len(s)

x in s

x not in s

isdisjoint(other)

issubset(other)

issuperset(other)

union(*others)

intersection(*others)

difference(*others)

symmetric_difference(other)

copy()

Create sets

A = {1, 2, 3, 4, 5}
B = {10, 3, 5, 9, 8}

A

Output: {1, 2, 3, 4, 5}

B

Output: {3, 5, 8, 9, 10}

Check the length of set A

len(A)

Output: 5

Test x for membership in set.

2 in A

Output: True

2 in B

Output: False

Test x for non-membership in set.

20 not in A

Output: True

5 not in B

Output: False

isdisjoint

isdisjoint(other) — Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set. Means returns whether two sets have a intersection or not

A.isdisjoint(B)

Output: False

issubset(other)

set <= other

Test whether every element in the set is in other.

A.issubset(B)

Output: False

issuperset(other)

set >= other

Test whether every element in other is in the set.

set > other

Test whether the set is a proper superset of other, that is, set >= other and set != other.

A.issuperset(B)

Output: False

Add item in set A

A = {1, 2, 3, 4, 5}
B = {10, 3, 5, 9, 8}
print(A)
print(B)

Output: {1, 2, 3, 4, 5}
{3, 5, 8, 9, 10}

A.add(12)print(A)

Output: {1, 2, 3, 4, 5, 12}

B

Output: {3, 5, 8, 9, 10}

remove(elem)

Remove element elem from the set. Raises KeyError if elem is not contained in the set.

A.remove(5)
A

Output: {1, 2, 3, 4, 12}

pop()

Remove and return an arbitrary element from the set. Raises KeyError if the set is empty.

A.pop()

Output: 1

A

Output: {2, 3, 4, 12}

discard(elem)

Remove element elem from the set if it is present.

A.discard(4)
A

Output: {2, 3, 12}

Set Union

union(s): Union of A and B is a set of all elements from both sets. Using the operator ‘|’ between 2 existing sets is the same as writing My_Set1.union(My_Set2)..

A|B

Output: {2, 3, 5, 8, 9, 10, 12}

A.union(B)

Output: {2, 3, 5, 8, 9, 10, 12}

Use union function on B

B.union(A)

Output: {2, 3, 5, 8, 9, 10, 12}

Set Intersection

intersection(*others)

set & other & …

Return a new set with elements common to the set and all others.

Intersection of A and B is a set of elements that are common in both the sets.

A & B

Output: {3}

A.intersection(B)

Output: {3}

B.intersection(A)

Output: {3}

Set Difference

difference(*others)

set — other — …

Return a new set with elements in the set that are not in the others.

A

Output: {2, 3, 12}

B

Output: {3, 5, 8, 9, 10}

Difference of the set B from set A(A — B) is a set of elements that are only in A but not in B.

A - B

Output: {2, 12}

A.difference(B)

Output: {2, 12}

B — A is a set of elements in B but not in A.

B - A

Output: {5, 8, 9, 10}

B.difference(A)

Output: {5, 8, 9, 10}

Symmetric Difference

set ^ other

Return a new set with elements in either the set or other but not both.

The symmetric difference between two sets is the set of all the elements that are either in the first set or the second set but not in both.

A ^ B

Output: {2, 5, 8, 9, 10, 12}

A.symmetric_difference(B)

Output: {2, 5, 8, 9, 10, 12}

B.symmetric_difference(A)

Output: {2, 5, 8, 9, 10, 12}

update(*others)

set |= other | …

Update the set, adding elements from all others.

A.update(B)
A

Output: {2, 3, 5, 8, 9, 10, 12}

intersection_update(*others)

set &= other & …

Update the set, keeping only elements found in it and all others.

A

Output: {2, 3, 5, 8, 9, 10, 12}

B

Output: {3, 5, 8, 9, 10}

A.intersection_update(B)
A

Output: {3, 5, 8, 9, 10}

difference_update(*others)

set -= other | …

Update the set, removing elements found in others.

A.difference_update(B)
A

Output: set()

clear()

Remove all elements from the set.

A = {1, 2, 3, 4, 5}
A

Output: {1, 2, 3, 4, 5}

A.clear()

Output: set()

copy()

Return a shallow copy of the set.

C = B.copy()
C

Output: {3, 5, 8, 9, 10}

Create another example to teach kids

In this example, we will create two sets of papa’s and mummy’s family. We will see which are common members in both the family. If new member comes in one family, how we will add new member. If one member is not there, how we will remove that member. How to get difference between both the family.

papa_family = {'dada', 'dadi', 'papa', 'mummy', 'john', 'priyanka', 'uncle', 'aunty', 'sara'}mummy_family = {'nana', 'nani', 'mama', 'mami', 'papa', 'mummy', 'john', 'priyanka', 'ratna'}print(papa_family)
print(mummy_family)

Output: {‘sara’, ‘john’, ‘dada’, ‘uncle’, ‘dadi’, ‘priyanka’, ‘papa’, ‘aunty’, ‘mummy’}
{‘mami’, ‘nana’, ‘john’, ‘nani’, ‘priyanka’, ‘ratna’, ‘papa’, ‘mama’, ‘mummy’}

All members in papa’s and mummy’s family

full_family_members = papa_family | mummy_family
print(full_family_members)

Output: {‘mami’, ‘sara’, ‘nana’, ‘john’, ‘dada’, ‘uncle’, ‘dadi’, ‘nani’, ‘priyanka’, ‘ratna’, ‘papa’, ‘mama’, ‘aunty’, ‘mummy’}

Common members in papa and mammy’s family

common_members = papa_family & mummy_family
print(common_members)

Output: {‘papa’, ‘john’, ‘priyanka’, ‘mummy’}

Aunty got a new baby boy ‘Aarav’. Add new member in papa’s family.

new_member = 'aarav'
papa_family.add(new_member)
print(papa_family)

Output: {‘sara’, ‘john’, ‘dada’, ‘uncle’, ‘dadi’, ‘priyanka’, ‘aarav’, ‘papa’, ‘aunty’, ‘mummy’}

My nana was suffering from chronic disease. He is no more now.

mummy_family.remove('nana')

After removing nana from mummy’s family.

print(mummy_family)

Output: {‘mami’, ‘john’, ‘nani’, ‘priyanka’, ‘ratna’, ‘papa’, ‘mama’, ‘mummy’}

What is difference in papa’s family

We have remove commom items,which is present in mummy’s family

#papa_family - mummy_family
#or
papa_family.difference(mummy_family)

Output: {‘aarav’, ‘aunty’, ‘dada’, ‘dadi’, ‘sara’, ‘uncle’}

Difference in mummy’s family

#mummy_family - papa_family
#or
mummy_family.difference(papa_family)

Output: {‘mama’, ‘mami’, ‘nani’, ‘ratna’}

All the members that are either in the papa’s family or in the mummy’s family but not in both.

#papa_family ^ mummy_family
#or
papa_family.symmetric_difference(mummy_family)

Output: {‘aarav’, ‘aunty’, ‘dada’, ‘dadi’, ‘mama’, ‘mami’, ‘nani’, ‘ratna’, ‘sara’,
‘uncle’}

That’s it, in this blog. If you have any question related to my blog, you can email me at nutanbhogendrasharma@gmail.com.

Thanks for reading.

--

--

Nutan

knowledge of Machine Learning, React Native, React, Python, Java, SpringBoot, Django, Flask, Wordpress. Never stop learning because life never stops teaching.