Python Set
Python Set is like a dictionary, an unordered collection of keys, held without any values. The set type is mutable , the contents can be changed using methods like add() and remove() . Sets do not contain duplicates, every element in a Python set can have only one occurrence in that particular set, no multiple occurrences are allowed. There are currently two built-in set types, Set and Frozenset .
example
output
Create a Set from Tuple
example
output
Create a Set from List
example
output
Sets are Mutable
The set type is mutable, the contents can be changed using methods like add() and remove().
example
output
Set.remove() remove elements from set.
example
output
Set Length
len() function returned the length of a set.
example
output
Union of Sets
In Python, Union operation can be performed on two Python sets using the operator or by using the method union(). Union of two sets x and y is another set that contains all distinct elements in sets x and x.
Using | Operator
example
output
Using union()
example
output
Intersection of Sets
In Python, Union operation can be performed on two Python sets using the operator & or by using the method intersection(). Intersection of two sets x and y is another set of elements those are present in both sets x and y (common to both of them).
Using & operator
example
output
Using intersection()
example
output
Difference of Sets
The difference() method returns the set difference of two sets. In Python, Difference operation can be performed on two Python sets using the operator - or by using the method difference().
Using - operator
example
output
Using difference()
example
output
Symmetric Difference of Sets
Symmetric difference of the sets is the set of elements those are not common to both the sets. The symmetric_difference() method using.
Using symmetric_difference()
example
output
Frozenset
A frozenset value is immutable: it's set up with the frozenset() function call, but once it's set up its contents cannot be altered.