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.
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.
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.
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.
The following code snippet explains the set intersection concept.
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,
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.
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.
The numbers 9 and 7 are unique in the set B and hence it alone is returned.
The set A is called the subset of B if all the elements of the set are in set B.
Since all the elements of the set a are present is b, a is the subset of b.
A set A is a superset of another set B if all elements of the set B are elements of the set A.
Since all the elements of the set b are present in the set a, set b is the superset of set a.
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.