Python frozenset() Function
frozenset() is a built-in Python function that creates an immutable set (frozenset).
The difference between frozenset and set is that frozenset is immutable: after creation, elements cannot be added, removed, or modified. Because of this immutability, frozenset can be used as a dictionary key or an element of a set.
Word meaning: frozenset is short for "frozen set", meaning an immutable set.
Basic syntax and parameters
Syntax format
frozenset(iterable)
Parameter Description
- Parameter iterable:
- Type: iterable
- Description: the iterable to convert to an immutable set.
Function description
- Return Value: returns a frozenset object.
- Special values: with no arguments, returns an empty frozenset.
Example
Example 1: creating a frozenset
Example
Create from a list
lst
=
[
1
,
2
,
3
,
2
,
1
]
fs
=
frozenset
(
lst
)
(
fs
)
Output: frozenset({1, 2, 3})
Create from a string
s
=
"hello"
fs
=
frozenset
(
s
)
(
fs
)
Output: frozenset({'h', 'e', 'l', 'o'})
Create from a dictionary (keys only)
d
=
{
"a"
:
1
,
"b"
:
2
}
fs
=
frozenset
(
d
)
(
fs
)
Output: frozenset({'a', 'b'})
Empty frozenset
fs
=
frozenset
(
)
(
fs
)
Output: frozenset()
Expected output:
frozenset({1, 2, 3})
frozenset({'h', 'e', 'l', 'o'})
frozenset({'a', 'b'})
frozenset()
Code analysis:
- frozenset removes duplicates automatically.
- It can be used with all kinds of iterables.
- frozenset is immutable and has no add, remove, or similar methods.
Example 2: uses of frozenset
Example
frozenset can be used as a dictionary key
d
=
{
frozenset
(
[
1
,
2
]
)
:
"A"
,
frozenset
(
[
3
,
4
]
)
:
"B"
}
(
d
)
Output: {frozenset({1, 2}): 'A', frozenset({3, 4}): 'B'}
frozenset can be an element of a set
s
=
{
frozenset
(
[
1
,
2
]
)
,
frozenset
(
[
3
,
4
]
)
}
(
s
)
Output: {frozenset({1, 2}), frozenset({3, 4})}
frozenset supports set operations (but does not modify the original set)
fs1
=
frozenset
(
[
1
,
2
,
3
]
)
fs2
=
frozenset
(
[
2
,
3
,
4
]
)
(
fs1 & fs2
)
Output: frozenset({2, 3}) intersection
(
fs1 | fs2
)
Output: frozenset({1, 2, 3, 4}) union
Expected output:
{frozenset({1, 2}): 'A', frozenset({3, 4}): 'B'}
{frozenset({1, 2}), frozenset({3, 4})}
frozenset({2, 3})
frozenset({1, 2, 3, 4})
The main use of frozenset is as a dictionary key or an element of a set.
Python3 built-in function