Set is a mutable, unordered collection of unique, hashable elements(may be of same or different types), which is not indexed.
x = set()
x = {2,3,0,'g'}
{}
is not possible as {}
is reserved for dictionary dict
objects
In [1]:
x = {1,2,5,3}
x
Out[1]:
Like any other collection, set
supports membership operators in
and not in
, elements of set
can be iterated. If A
and B
are 2 sets,Following is a list of other operations on set
A.union(B)
- returns $A\cup B$A.union_update(B)
- $A= A\cup B$A.intersection(B)
- returns $A\cap B$A.intersection_update(B)
- $A= A\cap B$A.isdisjoint(B)
- returns $A\cap B == \emptyset$A.issubset(B)
- returns $A\subseteq B$A.issuperset(B)
- returns $A\supseteq B$Other operations like set difference are also supported
In [2]:
x
Out[2]:
In [3]:
x.union([2,4,6])
Out[3]:
In [4]:
x.intersection([2,3])
Out[4]:
In [5]:
x.intersection_update([1,3,4])
In [6]:
x
Out[6]:
In many cases, it is required to have set of sets as in case of finding subsets of a set. Since set
is not hashable, it is not possible to have a set
as an element of set
. In this case frozenset
comes handy. The only difference between frozenset
and a set
is that frozenset
is immutable. We have to reassign value to it if we want to modify it.