Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Data types & structuresMiddleOccasionalTheory

What is a frozenset, and why would you use it instead of a set?

Answer

A frozenset is an immutable, hashable version of a set: once created, elements cannot be added or removed. Because it is hashable, a frozenset can be used as a dict key or as a member of another set, which a regular mutable set cannot. It is the right choice whenever a fixed collection of unique values needs to act as a lookup key, such as caching a function's result keyed by an unordered set of input flags.

Strong answer includes

  • immutable, hashable variant of set
  • usable as a dict key or set member
  • fits fixed collections used as lookup keys

Practical example

Python example
cache = {}

keyed by

Python example
frozenset(active_flags)

lets a memoization layer treat

Python example
{"a", "b"}

and

Python example
{"b", "a"}

as the same cache key regardless of insertion order.

#set#hashing#immutability

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules