Python frozenset()
Function
The frozenset() function in Python returns an immutable version of a set. Once created, you cannot add or remove elements from a frozenset. It is often used when you need a constant set that won’t change and can be used as a dictionary key or set element.
Syntax
frozenset([iterable])
Parameters:
iterable
– Optional. An iterable like list, set, tuple, or string. If no argument is passed, it returns an empty frozenset.
Returns:
- An immutable frozenset object containing the unique elements from the iterable.
Example 1: Create a Frozenset from a List
nums = [1, 2, 3, 2]
fset = frozenset(nums)
print(fset)
frozenset({1, 2, 3})
Note: Duplicate elements are automatically removed, just like a normal set.
Example 2: Frozenset with Strings
fset = frozenset("hello")
print(fset)
frozenset({'e', 'h', 'l', 'o'})
Use Case: Frozenset as Dictionary Keys
fset1 = frozenset([1, 2])
fset2 = frozenset([3, 4])
my_dict = {fset1: "Group A", fset2: "Group B"}
print(my_dict)
{frozenset({1, 2}): 'Group A', frozenset({3, 4}): 'Group B'}
Why? Because frozensets are immutable, they can be used as dictionary keys or elements of another set, unlike normal sets.
Common Mistakes
- Trying to modify a frozenset using
add()
orremove()
– will raise anAttributeError
. - Assuming it behaves exactly like a set in all situations — remember it is immutable!
Interview Tip
Use frozenset
when you want to store a group of items that must remain constant and be hashable (usable in keys, nested sets, etc).
Summary
frozenset()
creates an immutable set.- It removes duplicates like a normal set.
- It can be used in places where a hashable type is required (e.g., dict keys).
- Does not support
add()
,remove()
, or any modification methods.
Practice Problem
Create a frozenset from a tuple and try to add an element to it. What happens?
colors = ("red", "blue", "red", "green")
fcolors = frozenset(colors)
print(fcolors)
# Try this (will raise an error)
# fcolors.add("yellow")
frozenset({'green', 'blue', 'red'})