Table of Contents | |
Understanding Python frozenset()
Function
Python frozenset() is a built-in function that creates an immutable (unchangeable) set from an iterable object. Unlike regular sets that can be modified after creation, a frozenset, once created, cannot be altered – you can’t add or remove elements from it. This immutability makes frozensets useful when you need a set that can be used as a dictionary key or as an element in another set, as these scenarios require hashable (and, therefore, immutable) objects. Python frozenset() takes an iterable as input and returns a new frozenset containing the unique elements from that iterable.
Syntax of Python frozenset()
frozen_set = frozenset(iterable)
Explanation
frozen_set
: Variable will store the newly created frozenset object.frozenset()
: Built-in function that creates a frozenset.iterable
(optional): Iterable whose elements will be used to create the frozenset. It is used as input forfrozenset()
. If not provided, it returns an empty frozenset.
Example of Python frozenset()
my_set = {1, 2, 3}
frozen_set = frozenset(my_set)
print(frozen_set)
Explanation
my_set = {1, 2, 3}
: Creates a regular set namedmy_set
.frozen_set = frozenset(my_set)
: Creates a frozenset frommy_set
and assigns it tofrozen_set
.print(frozen_set)
: Prints the frozenset.
Output
frozenset({1, 2, 3})
frozenset()
Parameters
Python frozenset() function accepts a single parameter, which is an optional iterable. This iterable can be a set, list, tuple, string, or any other object that supports iteration. If you don’t provide an iterable, frozenset() returns an empty frozenset. The elements of the iterable will become the elements of the new frozenset, but any duplicate elements will be automatically removed because sets, by definition, only contain unique elements.
Syntax
frozen_set = frozenset(iterable)
Example
my_list = [1, 2, 2, 3, 4, 4, 4, 5]
frozen_set = frozenset(my_list)
print(frozen_set)
Explanation
my_list = [1, 2, 2, 3, 4, 4, 4, 5]
: Creates a listmy_list
with some duplicate elements.frozen_set = frozenset(my_list)
: Creates a frozenset frommy_list
, removing duplicates, and assigns it tofrozen_set
.print(frozen_set)
: Prints the frozenset.
Output
frozenset({1, 2, 3, 4, 5})
frozenset()
Return Type
Python frozenset() function returns a new frozenset object. A frozenset is an immutable version of a Python set, meaning that once it’s created, you cannot add or remove elements from it. If you provide an iterable to frozenset(), the new frozenset will contain the unique elements from that iterable. If you don’t give any argument, it returns an empty frozenset. The returned frozenset will always be immutable.
Syntax
frozenset_object = frozenset(iterable)
Example
empty_frozenset = frozenset()
print(empty_frozenset)
Explanation
empty_frozenset = frozenset()
: Creates an empty frozenset and assigns it toempty_frozenset
.print(empty_frozenset)
: Prints the empty frozenset.
Output
frozenset()
Python frozenset()
for Dictionary
When you use Python frozenset() with a dictionary, it creates a frozenset containing only the keys of the dictionary, not the values. This is because frozenset(), like set(), iterates over the dictionary’s keys by default. The order of the keys in the frozenset might not be the same as the order in the dictionary, as sets (and frozensets) are unordered collections. The returned frozenset will have the keys of the dictionary.
Syntax
frozen_set = frozenset(dictionary)
Example
my_dict = {"a": 1, "b": 2, "c": 3}
frozen_set = frozenset(my_dict)
print(frozen_set)
Explanation
my_dict = {"a": 1, "b": 2, "c": 3}
: Creates a dictionary namedmy_dict
.frozen_set = frozenset(my_dict)
: Creates a frozenset containing only the keys ofmy_dict
and assigns it tofrozen_set
.print(frozen_set)
: Prints the frozenset.
Output
frozenset({‘a’, ‘b’, ‘c’})
Python frozenset for Tuple
When you pass a tuple to Python frozenset(), it creates a frozenset containing all the unique elements from the tuple. The order of elements in the frozenset might not be the same as in the original tuple because sets, and therefore frozensets, are unordered. This conversion is useful when you need an immutable collection of unique items derived from a tuple.
Syntax
frozen_set = frozenset(tuple)
Explanation
frozen_set
: Variable will store the frozenset created from the tuple’s elements.frozenset()
: Function creates a frozenset.tuple
: Tuple you’re using to create the frozenset. It is the input parameter forfrozenset()
.
Example
my_tuple = (1, 2, 2, 3, 3, 3)
frozen_set = frozenset(my_tuple)
print(frozen_set)
Explanation
my_tuple = (1, 2, 2, 3, 3, 3)
: Creates a tuplemy_tuple
with duplicate elements.frozen_set = frozenset(my_tuple)
: Creates a frozenset frommy_tuple
, which automatically removes duplicates, and assigns it tofrozen_set
.print(frozen_set)
: Prints the frozenset.
Output
frozenset({1, 2, 3})
Python frozenset for List
When you apply Python frozenset() to a list, it creates a frozenset containing the unique elements from the list. Duplicates in the list are automatically removed because a frozenset, like a set, only stores unique elements. The order of elements in the resulting frozenset might not be the same as in the original list because sets and frozensets are unordered collections.
Syntax
frozen_set = frozenset(list)
Explanation
frozen_set
: Variable will store the frozenset created from the list’s elements.frozenset()
: Function creates a frozenset.list
: List you’re using to create the frozenset. It is used as input forfrozenset()
.
Example
my_list = [4, 4, 5, 6, 6, 6, 7]
frozen_set = frozenset(my_list)
print(frozen_set)
Explanation
my_list = [4, 4, 5, 6, 6, 6, 7]
: Creates a listmy_list
with some duplicate elements.frozen_set = frozenset(my_list)
: Creates a frozenset frommy_list
, removing duplicates, and assigns it tofrozen_set
.print(frozen_set)
: Prints the frozenset.
Output
frozenset({4, 5, 6, 7})
Frozenset Operations
Frozensets, being immutable sets, support various set operations like union, intersection, difference, and symmetric difference. You can use methods like .union(), .intersection(), .difference(), and .symmetric_difference() to perform these operations. Since frozensets are immutable, these operations return new frozensets containing the result of the operation, rather than modifying the original frozenset.
Syntax
result_frozenset = frozenset1.operation(frozenset2)
Explanation
result_frozenset
: Variable will store the new frozenset resulting from the operation.frozenset1
: First frozenset..operation()
: Method representing a set operation (e.g.,union
,intersection
).frozenset2
: Second frozenset. It is used as input foroperation()
.
Example
fs1 = frozenset([1, 2, 3])
fs2 = frozenset([3, 4, 5])
union_set = fs1.union(fs2)
print(union_set)
Explanation
fs1 = frozenset([1, 2, 3])
: Creates a frozensetfs1
.fs2 = frozenset([3, 4, 5])
: Creates another frozensetfs2
.union_set = fs1.union(fs2)
: Computes the union offs1
andfs2
, storing the result inunion_set
.print(union_set)
: Prints theunion_set
.
Output
frozenset({1, 2, 3, 4, 5})
Using frozenset as a Dictionary Key
One of the key features of a Python frozenset is that it can be used as a dictionary key. Because frozensets are immutable, they are hashable, a requirement for dictionary keys in Python. Regular sets, being mutable, cannot be used as dictionary keys. This property of frozensets allows you to use sets of items as keys in a dictionary, enabling more complex data structures and lookups.
Syntax
my_dict = {frozenset(iterable): value}
Explanation
my_dict
: Dictionary where the keys are frozensets.frozenset(iterable)
: Creates a frozenset fromiterable
, which is then used as a key inmy_dict
.value
: Value associated with the frozenset key.
Example
key = frozenset([1, 2, 3])
my_dict = {key: "value"}
print(my_dict[key])
Explanation
key = frozenset([1, 2, 3])
: Creates a frozenset namedkey
.my_dict = {key: "value"}
: Creates a dictionarymy_dict
withkey
as the key and “value” as the value.print(my_dict[key])
: Accesses the dictionary using the frozensetkey
and prints the associated value.
Output
value
Exceptions While Using the frozenset()
Method in Python
When using the Python frozenset() method, you might encounter exceptions if the iterable you provide contains unhashable elements. Since frozensets, like sets, require their elements to be hashable (immutable), attempting to create a frozenset with mutable elements like lists will raise a TypeError. It’s important to ensure that the elements you include in a frozenset are immutable to avoid this error.
Syntax
frozen_set = frozenset(iterable_with_unhashable_elements)
Explanation
frozen_set
: Variable would store the frozenset if no error occurred.frozenset()
: Function attempts to create a frozenset.iterable_with_unhashable_elements
: Iterable containing unhashable (mutable) elements. It is used as incorrect input forfrozenset()
.
Code Example
try:
my_frozenset = frozenset([[1, 2], [3, 4]])
print(my_frozenset)
except TypeError as e:
print(f"Error: {e}")
Explanation
try:
: Block attempts to execute code that might raise aTypeError
.my_frozenset = frozenset([[1, 2], [3, 4]])
: Attempts to create a frozenset from a list of lists, which will raise aTypeError
because lists are not hashable.print(my_frozenset)
: Print the frozenset if it were created successfully.except TypeError as e:
: Block catches theTypeError
if it occurs.print(f"Error: {e}")
: Prints the error message.
Output
Error: unhashable type: ‘list’
Conclusion
Python frozenset() function is a way to create immutable sets in Python. Unlike regular sets, frozensets cannot be changed after they are created, which makes them suitable for use as dictionary keys or elements of other sets. Python frozenset supports all the standard set operations (like union, intersection, etc.), but these operations always return a new frozenset instead of modifying an existing one. Understanding when and how to use frozensets is important for writing efficient and correct Python code, especially when dealing with scenarios that require hashable collections.