Better Programming

Advice for programmers.

Follow publication

Member-only story

What Are Frozen Sets in Python?

Jonathan Hsu
Better Programming
Published in
2 min readFeb 25, 2020

Photo by Jamie Street on Unsplash
  • Sets are an unordered, mutable data type where each value must be unique.
  • Tuples are an ordered, immutable data type where there is no restriction on duplicate values.

Just in case, mutable/immutable refers to being able/unable to change the value that is stored.

Wish you could have the best of both worlds in one data type? You can, with frozen sets.

What Are Frozen Sets?

Frozen sets are a native data type in Python that have the qualities of sets — including class methods — but are immutable like tuples.

To use a frozen set, call the function frozenset() and pass an iterable as the argument.

scores = {1,2}
scores.add(3) # {1,2,3}

If you pass a set to the function, it will return the same set, which is now immutable.

scores = {1,2}
frozen_scores = frozenset(scores)
frozen_scores.add(3)
# AttributeError: 'frozenset' object has no attribute 'add'

If you pass another data type such as a list, tuple, or string, then it will be treated as an iterable.

This means the value will be deconstructed into its individual parts, which will be reduced to a set of unique values that is immutable.

myList = [1,1,2,3,4]
myString = "Hello"
frozenList = frozenset(myList)
frozenString = frozenset(myString)
print(frozenList) # frozenset({1, 2, 3, 4})
print(frozenString) # frozenset({'e', 'l', 'H', 'o'})

Why Use Frozen Sets?

Honestly, there isn’t much to gain in terms of performance when choosing to use frozen sets.

The primary reason to use them is to write more clear, functional code. By defining a variable as a frozen set, you’re telling future readers: do not modify this!

Unfortunately, frozen sets cannot be declared with a character notation like sets with curly braces, lists with square brackets, or tuples with parentheses.

If you want to use a frozen set you’ll have to use the function to construct it.

Conclusion

Do you use frozen sets for your projects or production code? Do you find it’s not convenient enough to declare? Share your thoughts below and thanks for reading!

Responses (2)

Write a response