Python Set Subtraction Operation: A Beginner Guide – Python Tutorial

By | April 27, 2022

Set is python built-in data type, all elemens are unique in it. In this tutorial, we will introduce its subtraction operation for python beginners.

Python set data type

A python set looks like:

{1, 2, 3, 'c', 'a', 'b'}

We can generate a set data as follows:

x = set(<iter>)

For example, we can create a set using python list, tuple or a string.

x = [1, 2, 3, "a", "b", "c"]
print(set(x))

Python set subtraction operation

Set subtraction operation can remove some elements based on other set.

For example:

x = [1, 2, 3, "a", "b", "c"]
print(set(x))
y = [2,3]
z = set(x) -set(y)
print(z)

Run this code, we will see:

{1, 2, 3, 'c', 'a', 'b'}
{'a', 1, 'b', 'c'}

If both A and B are set data, A-B means we will remove elements from A in B.

Leave a Reply