Set and Frozenset in Python
Set and Frozenset in Python
frozenset() in Python
Python provides two built-in functions which are set() and frozenset(). These two functions are
used for creating sets but come with a few differences. Let’s see how you can use them.
Python set()
A set is an unordered and unindexed collection of unique elements. Sets
are mutable, you can change the elements using a built-in function like
add(), remove(), etc. Since the elements are mutable and not in order, they
don’t have hash values. So you can’t access the elements with the help of
index numbers.
Set is represented by curly braces like this {} or you can use set(). You can’t
use only curly braces to create an empty set, this will create a dictionary.
You can use set() if you want to create an empty set. Sets can include any
immutable data type like string, number, tuple, etc. You can also include
mutable data type like list, dictionary, etc.
Let’s go through some examples and see some of the operations you can
perform on sets:
If the element is not in the set which you want to remove then
discard() returns none while remove() will raise an error.
Python frozenset()
A frozenset is an unordered and unindexed collection of unique elements. It
is immutable and it is hashable. It is also called an immutable set. Since the
elements are fixed, unlike sets you can't add or remove elements from the
set.
Frozensets are hashable, you can use the elements as a dictionary key or as
an element from another set. Frozensets are represented by the built-in
function which is frozenset(). It returns an empty set if there are no
elements present in it. You can use frozenset() if you want to create an
empty set.
The above example shows you can't add a new element to the frozenset.
Let's see how can use a dictionary with frozenset:
Output:
Let's see other operations that you can perform on frozenset, you can also perform these
operations on normal sets:
# Membership testing