Set in python – difference, union, intersection, and subsets

In this article we are going to see about the set data type and various operations that are possible in this data type.

What is a set?

A set is a collection that is unordered and unindexed. In Python, sets are written with curly brackets. The elements in the set are always unique. so we can use the set class to remove duplicate elements from an iterable.

In python sets are written with curly braces.

set in python

Find unique elements using set

As said already, the elements in a set are always unique. We can use this property of sets to remove duplicate elements from iterable.

set – remove duplicate elements

The numbers list is having duplicate values. The set method removes the duplicate elements but the data type is also set. So I am converting the type back to list.

set intersection

The intersection of two sets is the elements that are common in both sets. This can be found by using both the intersection() method of the set and ‘&‘ operator.

What Is the Intersection of Two Sets?
set intersection

The following code snippet explains the set intersection concept.

set intersection in python

set union

Union (set theory) - Wikipedia
set union

The set union is nothing but the combination of all the elements from both sets. The set union can be found both by using the union() method or the ‘|‘ operator.

The code snippet to demonstrate set union is,

set union in python

set difference

The difference between the two sets in Python is equal to the difference between the number of elements in two sets. The function difference() returns a set that is the difference between two sets. 

A – B will return only the elements which are in A and not in B. (Intersections are avoided)

B – A will return only the images which are in B and not in A. (Intersections are avoided)

A- B or A.intersection(B) can be demonstrated with the following code snippet.

A – B

Here the elements 2 and 5 are unique in set A and hence it is returned.

B – A or B.intersection(A) can be explained with the following code snippet.

B – A

The numbers 9 and 7 are unique in the set B and hence it alone is returned.

subset

The set A is called the subset of B if all the elements of the set are in set B.

subset

Since all the elements of the set a are present is b, a is the subset of b.

Lesson on Subsets | Math Goodies

superset

set A is a superset of another set B if all elements of the set B are elements of the set A.

superset

Since all the elements of the set b are present in the set a, set b is the superset of set a.

Python Set Superset with Example – Python Tutorial – Code Destine

Elements in either set but not on both set

The ‘^‘ operator can be used to find the elements in either set but not on both set.